Home > Enterprise >  React: setTimeout not clearing within useEffect hook
React: setTimeout not clearing within useEffect hook

Time:12-07

Currently my app switches to the /about page after 5s of an intro on the /home page. I want to break this timeout if someone manually changes the page.

For this I have a state of introDisplayed which is false by default. By clicking on a link within the app the introDisplayed is becoming true

Why is the setTimeout within the useEffect not clearing? For reference I have listed all of my attempts on this matter.

clarification: I've tried adding introDisplayed alone to dependencies within useEffect, as well as with history and setIntroDisplayed as suggested by eslint and it doesn't change anything in this case

const Page = ({ introDisplayed, setIntroDisplayed }) => {

  const history = useHistory()

  const location = useLocation()

  // useEffect(() => {
  //   if (introDisplayed === false) {
  //     setTimeout(() => {
  //       setIntroDisplayed(true)
  //       history.push("/about")
  //     }, 5000)
  //   } else clearTimeout()
  // })
  // useEffect(() => {
  //   if (introDisplayed === false) {
  //     var timer = setTimeout(() => {
  //       setIntroDisplayed(true)
  //       history.push("/about")
  //     }, 5000)
  //   } else clearTimeout(timer)
  // })
  useEffect(() => {
    const timer = setTimeout(() => {
      setIntroDisplayed(true)
      history.push("/about")
    }, 1000)
    if (introDisplayed === true) {
      return () => clearTimeout(timer)
    }
  })

  return ()
}

CodePudding user response:

I think you've just forgotten to add dependency at useEffect().

useEffect(() => {
  if(introDisplayed === true) return;
  const timer = setTimeout(() => {
    setIntroDisplayed(true)
    history.push("/about")
  }, 1000)
  return () => clearTimeout(timer)
}, [introDisplayed])
  • Related