Skip to content

useRef

Creates and returns a mutable object (a ‘ref’) whose .current property is initialized to the passed argument.

This differs from useState in that state is immutable and can only be changed via setState which will cause a rerender. That rerender will allow you to be able to see the updated state value. A ref, on the other hand, can only be changed via .current and since changes to it are mutations, no rerender is required to view the updated value in your component’s code (e.g. listeners, callbacks, effects).

function App() {
const myRef = useRef(0);
return html`${myRef.current}`;
}

The ref object also has a .value property that stays in sync with .current. This makes it compatible with lit-html’s ref directive:

import { ref } from 'lit-html/directives/ref.js';
function App() {
const inputRef = useRef();
return html`<input ${ref(inputRef)} />`;
}
// After render: inputRef.current === inputRef.value === the <input> element

If you need a ref outside of a component context (e.g., in a class or module scope), use createRef:

import { createRef } from '@pionjs/pion';
const myRef = createRef(0);
console.log(myRef.current); // 0
console.log(myRef.value); // 0 (same as .current)

useRef

ParameterTypeDescription
initialValue--