Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 08 / Topic 1 of 6

A ref is a box that outlives a render, invisibly to React

useRef(initialValue) returns one object shaped exactly like { current: initialValue }. React hands back that same object on every re-render of this component instance - not a fresh one, the way useState's value would look if you mutated it directly. Mutating .current is instant and synchronous, and critically, React never finds out it happened. examples/01_ref_vs_state_no_rerender.jsx makes the difference impossible to miss by building the identical click counter twice:

// examples/01_ref_vs_state_no_rerender.jsx
export function ClickCounterWithRef() {
  const clickCountRef = useRef(0);

  function handleClick() {
    clickCountRef.current += 1;
    // No setState call here - React was never told anything changed, so it
    // never re-renders, so the text below never updates on screen.
  }

  return (
    <div>
      <p>Clicks (ref): {clickCountRef.current}</p>
      <button onClick={handleClick}>Add to wishlist</button>
    </div>
  );
}

Clicking ClickCounterWithRef's button three times really leaves "Clicks (ref): 0" on screen the entire time (examples/01_ref_vs_state_no_rerender.test.jsx) - clickCountRef.current genuinely is 3 by then, but nothing ever asked React to look at it again. ClickCounterWithState, identical except for useState and setClickCount, really shows "Clicks (state): 1", then "...: 3" after the same three clicks - because setState is the one thing that tells React "render again."

๐Ÿ” Going deeper: this is also why useRef is a deliberately small part, placed right after custom hooks and before context (see DESIGN-NOTES.md) - it is not a second, lesser useState. If you find yourself reading .current inside the JSX you return, so its latest value needs to show up on screen, that is useState's job, not a ref's.

Done here? The practice set for Part 8 โ€” including the solutions โ€” is on the part page.

Search the guide