0
Challenge · 23Hooks & Effects

Effect Cleanup

Coreused in ~90% of apps

An Effect that opens something but never closes it leaks: intervals stack up, listeners pile on, sockets stay open, and you set state on components that are already gone. Cleanup is how every Effect undoes itself.

Core idea. The function you RETURN from an Effect is its cleanup. React runs it before the Effect runs again (when dependencies change) and once more when the component unmounts — so every setup is paired with a teardown.
Playground, this isn't a screenshot
effect returns:
<ChatRoom />unmounted
messages received
0
ticking at 0× speed
open connections
none — all closed
effect timeline
Press Mount, then Unmount and Mount again.

With cleanup: every Unmount closes the connection it opened, so re-mounting always leaves exactly one — the counter ticks at 1× forever.

↑ play a little first, then dig in