useRef: Mutable Values & DOM References
useRef stores a mutable value that persists across renders without causing a re-render when changed. It is also commonly used to reference DOM nodes.
Use refs for values that do not belong in the rendered UI: timer IDs, imperative handles, previous values, or DOM nodes. If changing the value should update the screen, it usually belongs in state instead.
A ref's .current is mutable. Mutating it during render can make code difficult to reason about and should generally be avoided unless you have a very specific, well-understood pattern.
DOM ref
function SearchInput() {
const inputRef = useRef(null);
function focusInput() {
inputRef.current?.focus();
}
return (
<>
<input ref={inputRef} />
<button onClick={focusInput}>Focus</button>
</>
);
}💡 The ref provides an imperative escape hatch for a DOM operation without storing the element in state.
Key Takeaways
- Refs persist values without triggering renders.
- Use state for values that affect rendered output.
- Refs are useful for DOM access and imperative integrations.