Unable to set State in React in UseEffect With ‘popstate’ eventListener

I have a useEffect in React. In this useEffect I have a popstate eventListener. This eventListener successfully triggers if I visit the page, then visit another page, then press back to go back to the page with this code on it.

Although the eventListener trigger, if I try to set state inside the function attached to the event listener and then log the state to the console, the state is always undefined. This is not the case if I use a pageshow eventListener, so I am reasonably confident it has to do with popstate.

I have tried using a setTimeout around the state. I have tried moving the function outside the useEffect. I have also tried using useLayoutEffect. Neither work and the state is always undefined.

How can I use a popstate event listener to successfully set the state? I need to do something when the user arrives at the page from the back or forward button.

useEffect(() => {
  const handlePopState = () => {
     setSomeState("test value"); 
  };

  window.addEventListener('popstate', handlePopState);

  return () => {
    window.removeEventListener('popstate', handlePopState);
  };
}, []);