DEV Community

Discussion on: Why pressing the key works only once in my React project?

Collapse
erandakarachchi profile image
Eranda Kudalugodaarachchi
useEffect(() => {
    document.addEventListener('keypress', (e) => {
        if (e.code === 'Space') setItWorks(!itWorks)
    })
}, [itWorks])
Enter fullscreen mode Exit fullscreen mode

This might work. But haven't tested though.

Collapse
ptifur profile image
Yar Author

Thanks Eranda! Seems like it doubles the number of added key listeners with each press and soon the application stops responding.

Which means the answer is to remove keyListeners and clean up useEffect an some point? Not sure how, I've reached the limit of my Hooks understanding 😜

Collapse
erandakarachchi profile image
Eranda Kudalugodaarachchi • Edited on

When we add itWorks as a dependency to useEffect, It will re-render for each change of itWorks value. So here it will cause the number of event listeners to multiply at each change.
So as @Vesa Piittinen suggests it is a good idea to remove the listener if you are adding it in the useEffect hook.