0

In React

const compA = ()=>{
  const [loading,setLoading]=useState(false);
  useEffect(()=>{
    const blaBla="nothing";

    return ()=>{
      console.log("Component unmounted");
      setLoading(false)
    }
  },[])
  const handleSubmit=()=>{
    setLoading(true)
    window.location.href="//google.com";
  }
  return (
    <button onClick={handleSubmit} disabled={loading}>Link</button>
  )
}

This useEffect cleanup function will not fire when the user clicked on the button to open google.com

The question is how to get this cleanup work to do execute the setLoading(false) code when user navigate to external pages, so when the user click on the browser back button the button will be enabled again?

I need to clear/reset component state when the user navigate to external links

  • useEffect does not have visibility into the user leaving the page entirely, just into the lifecycle of that component. Check out this post about how you can use React Router to detect the user leaving the page: https://stackoverflow.com/questions/32841757/detecting-user-leaving-page-with-react-router – esinator Feb 15 '23 at 21:42

1 Answers1

0

I found a solution to this issue (resetting the state after navigating to external link)

const compA = ()=>{
  const [loading,setLoading]=useState(false);
  useEffect(()=>{
    const blaBla="nothing";

    return ()=>{
      console.log("Component unmounted");
      setLoading(false)
    }
  },[])
  const handleSubmit=()=>{
    setTimeout(()=>setLoading(true), 2000) // this will reset the state after 2s even if the user navigate to another external link, when he hit browser back button it will resume the timer and clear the state
    window.location.href="//google.com";
  }
  return (
    <button onClick={handleSubmit} disabled={loading}>Link</button>
  )
}

The solution is to update the state inside a setTimeout which will execute after a specific timeout, even though the user will be redirected to another page the application state remains in the browser memory and so when the user go back from the browser back button the timer will resume and clear the state