Refs hold mutable values that survive re-renders without triggering updates—DOM nodes, timer IDs, previous prop snapshots. Use them when you need imperative access: focus an input, measure width, integrate a non-React chart library.
useRef
const inputRef = React.useRef(null);
React.useEffect(() => {
inputRef.current?.focus();
}, []);
return <input ref={inputRef} />;
Ref vs state
- Changing
ref.currentdoes not re-render - State changes schedule a render—use for UI that must update on screen
Callback refs
ref={(node) => ...} runs when the node mounts/unmounts—handy when parent and child need the same element reference dynamically.
Important interview questions and answers
- Q: Can you store anything in a ref?
A: Yes—DOM nodes, timers, or arbitrary mutable boxes; avoid storing derived UI that should be state. - Q: Why not use document.querySelector in components?
A: Breaks with multiple instances and SSR; refs tie behavior to the correct element instance.
Self-check
- When should focus management use a ref?
- Why does updating a ref not re-render the component?