useRef
container persisting across renders
- the container persists until the component unmounts.
- it holds mutable data.
- data mutation does not trigger a re-render.
- it is made of a unique property called
current
.
const x = useRef(33)
x.current // 33
x.current += 1 // 34
targeting a DOM element
a child component in the tree may declare itself as the target of the ref:
<input ref={myInputRef} />
React mutates the reference as soon as the target element has mounted in the DOM. At that point, current
targets the element, which is an HTMLElement. We may provide a more specific type such as HTMLInputElement
Typescript example
const myInput = useRef<HTMLInputElement>(null)
// ..
<input ref={myInput}/>
Even though current
holds null before targeting the element, we may omit null from the type parameters.
We may now use the DOM APIs relevant to the specific HTML element.
myInput.current.innerText
myInput.current.innerHTML
myInput.current.value