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:
const modal_state_ref = React.useRef(modal_state);
React.useEffect(() => {
modal_state_ref.current = modal_state;
}, [modal_state]);
React.useEffect(() => {
const listener = () => {
console.log(`state in handler is ${modal_state_ref.current}`);
};
window.addEventListener('customEvent-modal-opening', listener);
return () => {
window.removeEventListener('customEvent-modal-opening', listener);
}
}, []);
I believe I understand about closures and how the value in the event handler is from a "snap shot" 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.