React hooks - right way to clear timeouts and intervals

ZiiMakc picture ZiiMakc · Oct 31, 2018 · Viewed 72.2k times · Source

I don't understand why is when I use setTimeout function my react component start to infinite console.log. Everything is working, but PC start to lag as hell. Some people saying that function in timeout changing my state and that rerender component, that sets new timer and so on. Now I need to understand how to clear it's right.

export default function Loading() {
  // if data fetching is slow, after 1 sec i will show some loading animation
  const [showLoading, setShowLoading] = useState(true)
  let timer1 = setTimeout(() => setShowLoading(true), 1000)

  console.log('this message will render  every second')
  return 1
}

Clear in different version of code not helping to:

const [showLoading, setShowLoading] = useState(true)
  let timer1 = setTimeout(() => setShowLoading(true), 1000)
  useEffect(
    () => {
      return () => {
        clearTimeout(timer1)
      }
    },
    [showLoading]
  )

Answer

ZiiMakc picture ZiiMakc · Oct 31, 2018

Return function in useEffect runs every time useEffect runs (except first run on component mount). Think about it as every time there is new useEffect execution, the old one get deleted.

This is a working way to use and clear timeouts or intervals:

export default function Loading() {   
     const [showLoading, setShowLoading] = useState(false)
      
     useEffect(
        () => {
          let timer1 = setTimeout(() => setShowLoading(null), 1000)
    
          // this will clear Timeout when component unmount like in willComponentUnmount
          return () => {
            clearTimeout(timer1)
          }
        },
        [] //useEffect will run only one time
           //if you pass a value to array, like this [data] than clearTimeout will run every time this value changes (useEffect re-run)
      )

 return showLoading && <div>I will be visible after ~1000ms</div>
}

If you need to clear timeouts or intervals somewhere outside:

export default function Loading() {   
     const [showLoading, setShowLoading] = useState(false)
      
     const timerToClearSomewhere = useRef(null) //now you can pass timer to another component

     useEffect(
        () => {
          timerToClearSomewhere.current = setInterval(() => setShowLoading(true), 50000)
    
          return () => {
            clearInterval(timerToClearSomewhere.current)
          }
        },
        []
      )

  //here we can imitate clear from somewhere else place
  useEffect(() => {
    setTimeout(() => clearInterval(timerToClearSomewhere.current), 1000)
  }, [])

 return showLoading ? <div>I will never be visible because interval was cleared</div> : <div>showLoading is false</div>
}

Article from Dan Abramov.