Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.5 — The Lifecycle of an Effect
React · Example 2 of 2

One effect per concern

Changing the server makes Combined log a second visit to #general that never happened, polluting the analytics. Split only reconnects. Notice also that both cleanups run before any new setup.

A component mounts, updates and unmounts, but an effect only does two things: start syncing and stop syncing; think of each effect on its own, list the reactive values it reads, and React re-syncs it whenever one of them changes.

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

A Weather component receives city and has units state ("C" or "F"). It subscribes with const off = weatherFeed.subscribe(city, units, setData). Write the effect.

02

Split this effect: useEffect(() => { document.title = name; const id = setInterval(poll, delay); return () => clearInterval(id); }, [name, delay]);

Explain it without notes

01

How is an effect's lifecycle different from a component's lifecycle?

02

What makes a value reactive? Give examples of reactive and non-reactive values.

03

Why should you split an effect that does two unrelated things?

04

Why is thinking "on mount" dangerous when writing effects?

One effect per concern

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Combined: analytics, visited #general
Combined: connect #general via eu
Split: analytics, visited #general
Split: connect #general via eu
--- change server
Combined: disconnect #general via eu
Split: disconnect #general via eu
Combined: analytics, visited #general
Combined: connect #general via us
Split: connect #general via us