A component tracks how many keys have been pressed and how many times a button has been clicked. Each keypress should add exactly 1 to the key count regardless of how many times the button has been clicked.
Press a key - the count increments normally. Click Re-render, then press keys again - the count jumps by more than 1 per keypress. The more times Re-render is clicked, the larger the jump per keypress becomes.
Each time the effect runs, it adds a listener - what happens to the previous one?
Each time the effect runs, it adds a listener - what happens to the previous one?
Why this fixes it
Each time clicks changed, the effect registered a new keydown listener on window without removing the previous one - because there was no cleanup return, every Re-render click left one more live listener attached, and a single keypress triggered all of them simultaneously. Adding return () => window.removeEventListener('keydown', handleKey) gives React a cleanup to run before the effect fires again, which tears down the old listener before the new one is attached. At any point exactly one listener is active, so each keypress produces exactly one increment regardless of how many times the button has been clicked.