const [isToSave, setisToSave] = React.useState(false)
const myStateRef = React.useRef(isToSave);
React.useEffect(() => {
window.addEventListener('set-is-to-save', () => {
setisToSave(!myStateRef.current)
}, false);
return () => {
window.removeEventListener('set-is-to-save', () => {
setisToSave(!myStateRef.current)
});
}
}, [])
function handleOnClick(e: React.MouseEvent<HTMLDivElement>): void {
myStateRef.current=!isToSave
setisToSave(myStateRef.current)
}
handleOnClick function is called by the onClick for one of the component and it seems to be working fine. But, whenever I try to change the state from independent components using event triggers, the state of isToSave doesn't change.
For this simple usecase, you dont have to maintain state using useRef:
You can look at my quick test on my code that triggers a custom event here:
https://codesandbox.io/s/brave-https-4q6wd?file=/src/App.js
Basically if you use the state update with callback, it should work:
window.addEventListener('set-is-to-save', () => {
setisToSave((val) => !val)
}, false);
P.S: Be careful with custom events and security. If the communication is within same application, you should be using context or other state management.