In my job I have to make an http request when someone leaves the page. My idea was to do this request when the component of that page unmounts.
If I understand it correctly this can be done by putting logic in the return function of useEffect. When I do this it triggers at the right time, but the state values I want to use are not up-to-date. Is there a way to get up-to-date values?
useEffect(() => {
return () => {
//this runs on unmount
// but the state changes that happened are not registered it seems
}
}, [])
I have created a simple example in codesandbox: when you change the state from 4 to 8 and then hide the component. the NUM value in the unmount is still 4 (check console log). How can I get the current state value when I unmount the component?
https://codesandbox.io/live/b6e65d13114
https://codesandbox.io/s/loving-galois-okb0b (not sure which link to share is best)