Command Palette

Search for a command to run...

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

Clear the interval when the stopwatch leaves

Hiding the stopwatch unmounts it, so React calls the cleanup and the interval stops: zero stray ticks. Click Show to start a fresh stopwatch (new state, new interval).

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?

Clear the interval when the stopwatch leaves

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

setup: start the interval
cleanup: clear the interval
ticks after it was removed: 0