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

Trap 3: an object dependency makes an effect loop

Without the safety stop this would render forever. React counts nested updates from effects and, past 50, prints the warning below. The page still works, but the CPU never rests.

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 3: an object dependency makes an effect loop

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
renders so far: 61