Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.2 — Effect Dependencies
React · Example 3 of 3

An object made during render re-runs the effect every time

Toggling dark mode re-renders both children. BadSearch gets a fresh options object each time, so its effect re-runs for nothing. GoodSearch depends on the string and stays quiet. In a real app that wasted effect would be a network request.

The dependency array tells React which values an effect reads, so it can skip re-running the effect when none of them changed; React compares each one with Object.is, which is why new objects and functions made during render re-run the effect every time.

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 5 hands-on exercises with automatic checks.

Practice questions

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

01

This effect re-runs after every render. Fix it without disabling the linter: ``jsx function Room({ roomId }) { const config = { roomId, retries: 3 }; useEffect(() => { console.log("connect", config.roomId, config.retries); }, [config]); return null; }

02

Make this ticker's dependency array honest and empty: useEffect(() => { const id = setInterval(() => setCount(count + 1), 1000); return () => clearInterval(id); }, [count]);

Explain it without notes

01

Explain the three forms of the dependency array and when the effect runs for each.

02

How does React decide whether a dependency changed? What consequences does that have for objects and functions?

03

What is a reactive value? Which values don't need to be dependencies?

04

The linter asks you to add a dependency, but adding it makes the effect re-run too often. What do you do?

An object made during render re-runs the effect every time

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

BadSearch effect: searching react
GoodSearch effect: searching react
--- toggle 1 (query did not change)
BadSearch effect: searching react
--- toggle 2 (query did not change)
BadSearch effect: searching react