title: How to access state inside custom event listener
body: <p>I have spent time studying the details of other posts about this subject yet there is something I still do not understand. I am hoping I can receive some assistance to see this more clearly. Specifically, I would like to learn how to obtain the current state value inside a custom event handler. Here is some simplified code:</p>
  <pre><code>const modal_state_ref = React.useRef(modal_state);
  
  React.useEffect(() =&gt; {
      modal_state_ref.current = modal_state;
  }, [modal_state]);
  
  React.useEffect(() =&gt; {
      const listener = () =&gt; {
           console.log(`state in handler is ${modal_state_ref.current}`);
      };
      window.addEventListener('customEvent-modal-opening', listener);
      return () =&gt; {
          window.removeEventListener('customEvent-modal-opening', listener);
      }
  }, []);
  </code></pre>
  <p>I believe I understand about closures and how the value in the event handler is from a &quot;snap shot&quot; of the state at the time the event handler is created. I thought, however, that the ref, being an object, would always be reference to the location in memory, so always have the updated value. I'm at a lost for how to proceed.</p>