Accessing React State in Event Listeners with useState and useRef hooks
If you’re using React hooks in a component with an event listener, your event listener callback cannot access the latest state. We can incorporate useRef to solve this problem.
In this simple example, we are trying to access our state on a double-click event:
If you try this out you will see the listener only has access to the initial state, so it will always log: state in handler: 0 As explained in this Stack Overflow post, it’s because the listener belongs to the initial render and is not updated on subsequent rerenders.
So what can we do? We could go back to a class component where this.state.myState would always contain the latest state:
But we want to use Hooks, so what we can do is implement the useRef hook. Here we have our event handler example, updated with useRef:
What we’re doing is initializing myStateRef (a useRefhook) with the value in myState (a useState hook). Then we add a function to update both myState and the current property of myStateRef. CallmyStateRef.current and you will have the latest value.
Hope you find this useful. Again, thanks to this StackOverflow post for the implementation details and here are the React docs on useRef.

