React - useEffect to detect page exit
We can detect the page exit in useEffect Hooks
1
2
3
4
5
6
7
8
9
10
const [state, setState] = useState(null)
useEffect(() => {
let cancelled = false
// do something
// if there is any async code in here,
// we can use the cancelled flag to detect whether user left this page
return () => {cancelled = true}
}, [state])