BeginnerCoder

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.

Want it another way?
Task

Keep saved.current pointing at the newest callback. The number should keep growing 1, 2, 3… instead of sticking at 1.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with React Foundations

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.