Refs
Remember non-render data and access DOM nodes without causing rerenders.
A ref retains a mutable value between renders without triggering a render when it changes. Use it for DOM nodes, timers, and integration objects—not visible state.
Focus a DOM node
Search.tsx
function Search() {
const inputRef = useRef<HTMLInputElement>(null);
return <><input ref={inputRef} /><button onClick={() => inputRef.current?.focus()}>Focus search</button></>;
}
React sets current after committing the DOM. Read or write refs in event handlers and effects rather than during rendering.
Store an imperative value
Timer.tsx
const timerRef = useRef<number | undefined>(undefined);
function restart() {
window.clearTimeout(timerRef.current);
timerRef.current = window.setTimeout(save, 500);
}
Keep this
Use refs as an escape hatch for non-render values and narrow DOM operations; keep declarative data in props and state.
Your place is saved on this device.