Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.3 — Cleaning Up Effects
React · Example 3 of 3

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.

01

Write a useEffect that logs tick every second while the component is on screen and stops on unmount.

02

Write an OnlineStatus component that shows Online or Offline using the window online and offline events, with a proper cleanup.

Explain it without notes

01

When exactly does React run an effect's cleanup function?

02

Why does the cleanup in a chat room effect disconnect from the old room, not the new one?

03

List the cleanup that matches each of: setTimeout, setInterval, addEventListener, a subscription, fetch.

04

What happens if you forget a cleanup for an interval that calls a state setter? Does React warn?

Switching rooms: cleanup, then the new setup

Preview

Press Run to see the page.

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