Update state from event listener in useEffect
See original GitHub issueAm I allowed to update state from event listener ?
useEffect(() => {
window.addEventListener("keydown", () => {
updateState("something);
});
return () => window.removeEventListener("keydown", listener);
}, [])
I’m asking this question, because it seems that doing it this way, will trigger full update on all hooks created with useSelector
.
ps. Please let me know if full blown codesandbox example is needed
Issue Analytics
- State:
- Created 3 years ago
- Comments:8 (5 by maintainers)
Top Results From Across the Web
How to register event with useEffect hooks? - Stack Overflow
The best way to go about such scenarios is to see what you are doing in the event handler. If you are simply...
Read more >Accessing React State in Event Listeners with useState and ...
What we're doing is initializing myStateRef (a useRef hook) with the value in myState (a useState hook). Then we add a function to...
Read more >Handle React state inside an event listener callback
To do that you need to listen to keydown events by doing this: useEffect(() => { document.addEventListener('keydown', navigate)
Read more >Using window.addEventListener with react hooks
This is a quick post explaining best practices for using react hooks with addEventListener. Generally speaking you should try to avoid adding event...
Read more >Separating Events from Effects - React Docs
Unlike event handlers, Effects re-synchronize if some value they read, like a prop or a state variable, is different from what it was...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Published: https://www.npmjs.com/package/react-tracked/v/1.4.1
Thanks for your reporting!
Works on
2.0.0-alpha4
.Thanks a lot! 😃