Command Palette

Search for a command to run...

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

Any reactive value change re-synchronises

The component never unmounts here. Its effect still stops and starts twice: once because state (host, through serverUrl) changed, once because a prop (roomId) changed. The effect doesn't care which.

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?

Any reactive value change re-synchronises

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

start syncing: #general at https://localhost:1234
--- switch server
stop syncing: #general at https://localhost:1234
start syncing: #general at https://chat.example:1234
--- switch room
stop syncing: #general at https://chat.example:1234
start syncing: #travel at https://chat.example:1234