Skip to the page

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.

The notes

What you must know

  • Changing ref.current does 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.current during render (except lazy init if (ref.current === null) ref.current = create()); the Compiler's refs lint 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 with null.
  • TypeScript in React 19: useRef needs 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 = value during 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

  1. What is the difference between useRef and useState?
  2. Implement a usePrevious(value) hook.
  3. Can you drive rendering with useRef instead of useState?
  4. What are callback refs, and what changed in React 19?
  5. Is your usePrevious correct under concurrent rendering and StrictMode?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview