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 6 of 6

When NOT to reach for a ref

A ref can read a DOM node's current value, which makes it tempting to use instead of a controlled input (Part 5) - right up until the screen needs to show something that depends on that value while the user is still interacting. examples/06_when_not_to_use_ref.jsx puts the mistake and its fix side by side:

// examples/06_when_not_to_use_ref.jsx - broken
export function FareCalculatorWithRefBroken() {
  const kmRef = useRef(null);
  const fare = Number(kmRef.current?.value || 0) * 12; // read once, at render time
  return (
    <div>
      <input ref={kmRef} type="number" placeholder="Distance in km" />
      <p>Fare: ₹{fare}</p>
    </div>
  );
}

Typing "10" into this input really leaves "Fare: ₹0" on screen the entire time (examples/06_when_not_to_use_ref.test.jsx) - typing changes the real DOM input's value, but nothing about that keystroke tells React to re-render, so fare is computed exactly once, at mount, from whatever kmRef.current.value was then (empty). FareCalculatorWithStateFixed, using useState/onChange the way Part 5 already teaches, recalculates the fare on every keystroke correctly, because setKm is the thing that actually triggers a re-render. FareCalculatorReadOnSubmit shows the one case a ref on an input genuinely is fine: reading kmRef.current.value exactly once, inside a submit handler - a moment something else (the form submission) already re-renders for, never used to drive what's shown live on every keystroke.

The rule: if a value needs to be shown, recalculated, or reacted to as the user interacts, it belongs in useState. A ref is for a DOM handle, or for a value some other piece of code reads later, outside of render - never for something this component's own JSX needs to reflect live.

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

Search the guide