Accessing React State in Event Listeners with useState and useRef hooks

Bryan Grill
Nov 4 · 2 min read
Clothes and hats on hooks. Get it, hooks??
Clothes and hats on hooks. Get it, hooks??
Photo by Annie Spratt on Unsplash

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.

geographIT

Technical thoughts from the team at geographIT a division of EBA Engineering

Bryan Grill

Written by

developer @geographIT — frontend, backend, devops

geographIT

Technical thoughts from the team at geographIT a division of EBA Engineering

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade