Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 26.3 — Hooks Traps: Stale Closures, Effect Loops and Dependencies
React · Example 1 of 6

Trap 1: the interval that sticks at 1, and the fix

Both intervals tick five times. The stale one sets 0 + 1 five times; the fixed one adds one to the latest value each time.

Most hooks bugs come from three mistakes: a function that keeps reading values from an old render (a stale closure), an effect whose dependencies change every render (an effect loop), and an effect that sets something up without cleaning it up; each has a reliable fix.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Fix this so the countdown reaches 0: useEffect(() => { const id = setInterval(() => setLeft(left - 1), 1000); return () => clearInterval(id); }, []);

02

This effect loops. Fix it without disabling the lint rule: const filters = { tag }; useEffect(() => { setRows(applyFilters(all, filters)); }, [filters]);

03

Add the missing cleanup: useEffect(() => { document.addEventListener("keydown", onKey); }, [onKey]);

Explain it without notes

01

What is a stale closure in React? Give an example and three ways to fix it.

02

Why does an object in the dependency array cause an effect to run every render?

03

What does a missing effect cleanup cause, and how does StrictMode help you find it?

04

When would you use useEffectEvent instead of adding a value to the dependency array?

Trap 1: the interval that sticks at 1, and the fix

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Stale: 1
Fixed: 5