Switching rooms: cleanup, then the new setup
Each cleanup closes over the connection of its own run, so switching to travel disconnects from general (the old value), not from travel. Closing the chat runs the last cleanup.
The function an effect returns is its cleanup: it stops what the effect started (timers, subscriptions, event listeners, connections, requests), and React runs it before the effect runs again and when the component is removed.
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.
Write a useEffect that logs tick every second while the component is on screen and stops on unmount.
Write an OnlineStatus component that shows Online or Offline using the window online and offline events, with a proper cleanup.
Explain it without notes
When exactly does React run an effect's cleanup function?
Why does the cleanup in a chat room effect disconnect from the old room, not the new one?
List the cleanup that matches each of: setTimeout, setInterval, addEventListener, a subscription, fetch.
What happens if you forget a cleanup for an interval that calls a state setter? Does React warn?
Preview
Console
Nothing logged yet.Expected console output
connect to #general
--- switch to travel
disconnect from #general
connect to #travel
--- close the chat
disconnect from #travel