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.
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.
Split this effect: useEffect(() => { document.title = name; const id = setInterval(poll, delay); return () => clearInterval(id); }, [name, delay]);
Explain it without notes
How is an effect's lifecycle different from a component's lifecycle?
What makes a value reactive? Give examples of reactive and non-reactive values.
Why should you split an effect that does two unrelated things?
Why is thinking "on mount" dangerous when writing effects?
Preview
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