'React Router Dom v6 Detect user leave page and do somthing

I want when user leave the page our go to other routes a dispatch happen

useEffect(()=>{
  if(userLeave){
     dispatch(clearData())
  }
},[userLeave])

our any other examples if you have an idea where i can do a dispatch when user leave the page or go to other routes



Solution 1:[1]

try this, i think this might work.

       window.addEventListener("beforeunload", function (e) {
            e.preventDefault();
            e.returnValue = '';
            dispatch(clearData())
        })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eisa Rezaei