Refs and imperative code · mid
useRef: refs vs state, usePrevious and callback refs
A ref is a mutable box ({ current }) that survives renders but does not trigger a render when changed, so use it for DOM nodes and instance values like timer ids, never for anything shown on screen.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Changing
ref.currentdoes not re-render. If the screen must show it, it is state. - Good uses: DOM nodes (focus, measure, scroll), timer and request ids, the latest callback for an interval, an
AbortController, third-party widget instances. - Do not read or write
ref.currentduring render (except lazy initif (ref.current === null) ref.current = create()); the Compiler'srefslint rule flags it. - Classic
usePrevious:const ref = useRef(); useEffect(() => { ref.current = value; }); return ref.current;returns the value from the previous commit. - Callback refs:
ref={(node) => {...}}is called with the node on attach. In React 19 it can return a cleanup function; React then calls the cleanup on detach instead of calling the ref withnull. - TypeScript in React 19:
useRefneeds an argument (useRef(null)), and ref callbacks must not implicitly return a value (use a block body). - "Can you render a screen with useRef?" -> you can store data in it, but the UI will not update when it changes unless something else re-renders; forcing updates on top of refs is an anti-pattern.
The red pen
Common traps: mistake → fix
Mistake: "Refs are like instance variables, so use them as hidden state"
Fix: the UI goes out of sync.
Mistake: "Writing
ref.current = valueduring render is fine"Fix: render must be pure; React may render without committing.
Mistake: "Ref callbacks are always called with null on unmount"
Fix: in React 19, if you return a cleanup, React calls the cleanup instead.
Easy to hard
Questions interviewers ask, easy to hard
- What is the difference between
useRefanduseState? - Implement a
usePrevious(value)hook. - Can you drive rendering with
useRefinstead ofuseState? - What are callback refs, and what changed in React 19?
- Is your
usePreviouscorrect under concurrent rendering and StrictMode?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.