Reputation: 631
I have this hook:
useEffect(() => {
window.addEventListener('keydown', handleKeyPress);
return () => window.removeEventListener('keydown', handleKeyPress);
}, [props.tps])
For some reason, though, on the associated key press, the handleKeyPress function is called twice. I tried adding handleKeyPress as a dependency and that does not work, either. Any ideas?
Upvotes: 1
Views: 2258
Reputation: 21
Check your reactStrictMode
config, if it's true
change it to false
.
In my case I use NextJs
and it's located in next.config.js
.
reactStrictMode
only affect development only and not in production.
Upvotes: 0
Reputation: 1581
I saw this late but for others who may have this problem:
it is probably because of React.StrictMode
inside index.js
and it is an intentional thing when using hooks.
here is the reference
Upvotes: 3
Reputation: 343
props.tps
is not doing anything there, you need to delete the props.tps
from the dependency array because:
1.- The event listener (as it's not from the component itself but from window
) should be created on the "componentDidMount" or what's equivalent an empty dependency array.
2.- The values on the dependency array should be also inside the useEffect function to make it work properly.
Try taking it out the dependency array.
Upvotes: 0
Reputation: 4173
I am not sure why you added props.tps
, but try to remove it from dependency arrays.
Upvotes: 0