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

A ref as a mutable instance variable: an interval id and a previous value

Not every ref points at the DOM. A ref is also the right place for a value a component needs to keep around between renders, that a different piece of code reads later, and that should never, by itself, cause a re-render. examples/04_interval_and_previous_value_refs.jsx's PriceTicker needs two of these:

// examples/04_interval_and_previous_value_refs.jsx
const intervalIdRef = useRef(null);       // so handleTogglePause can clear it later
const previousPriceRef = useRef(startingPrice); // so this render can diff against "before"

useEffect(() => {
  previousPriceRef.current = price; // updated AFTER this render is painted
}, [price]);

useEffect(() => {
  if (isPaused) return;
  intervalIdRef.current = setInterval(() => setPrice((c) => c - 5), 1000);
  return () => clearInterval(intervalIdRef.current);
}, [isPaused]);

intervalIdRef is never shown on screen - it exists purely so the cleanup function (and, in a more complex component, a separate button handler) can find the exact interval this effect started. previousPriceRef is deliberately updated after the price that triggered this render, inside its own effect, so the JSX being rendered right now can compare the current price against what it was a moment ago without that comparison itself triggering another render. Advancing a fake clock by one second on a running PriceTicker really drops the price from ₹1000 to ₹995 and reports "down ₹5" (examples/04_interval_and_previous_value_refs.test.jsx); clicking "Pause ticker" really stops the ticking (vi.getTimerCount() reads 0 right after, not just "looks paused" while a timer keeps running underneath), and clicking "Resume ticker" really starts a fresh interval from the current price.

🔍 Going deeper: this is the closest useRef comes to a class component's this.someField - a plain, mutable slot an instance owns for its own bookkeeping, never meant to drive what gets rendered. If a later lesson's state-machine logic (Part 10's useReducer) ever needs "the previous state" for a transition, this is the same technique, just inside a reducer instead of a component.

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

Search the guide