Lesson 24 — useInterval hook
Timers without stale values
A stale closure happens when a function keeps seeing old values: the interval was set up with the first render's callback, so it reads n = 0 forever. The fix is a ref — useRef gives a box (ref.current) that survives re-renders without causing them. Save the newest callback into the ref on every render, and let the interval always call ref.current.
const latest = useRef(fn);
latest.current = fn; // updated every render
Why it matters: this pattern (popularised as useInterval) fixes a whole family of "my timer is stuck" bugs.
Keep saved.current pointing at the newest callback. The number should keep growing 1, 2, 3… instead of sticking at 1.
A quick 3-question quiz on this lesson — instant feedback.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based React Foundations courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for React Foundations books — check the publication year so the examples match current versions.
Search Amazon →