Command Palette

Search for a command to run...

Hectal
Phase 7: Effects
React · Exercise 3 of 5 PreviousNext
Intermediate

A keyboard listener without leaks

KeyCounter counts how many times the k key is pressed anywhere on the page, shown in #count. Its listener logs k pressed each time it handles a k.

The button #toggle hides and shows the counter. Right now, hiding it leaves the listener attached to window, so k pressed keeps being logged after the counter is gone (and showing it again adds a second listener).

Fix the effect so the listener is removed when the counter is hidden.

What Check tests

  1. Pressing k twice shows 2
  2. After hiding, pressing k logs nothing
  3. Shown again, it starts at 0 and counts each press once
  4. The cleanup removes the listener

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Your page

Press Run to see the page.

Console

Nothing logged yet.