question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Update state from event listener in useEffect

See original GitHub issue

Am 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:closed
  • Created 3 years ago
  • Comments:8 (5 by maintainers)

github_iconTop GitHub Comments

2reactions
dai-shicommented, Jun 23, 2020

Published: https://www.npmjs.com/package/react-tracked/v/1.4.1

Thanks for your reporting!

1reaction
gtanczykcommented, Jun 23, 2020

Works on 2.0.0-alpha4.

Thanks a lot! 😃

Read more comments on GitHub >

github_iconTop 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 >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found