Command Palette

Search for a command to run...

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

Add and remove a window listener

The scripted key presses go to window. After the logger is removed, pressing b logs nothing from it, because the cleanup removed the exact listener the setup added. Click inside the preview and press keys to try it.

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?

Add and remove a window listener

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

listener added
key: a
listener removed
pressed b after removal