When to return from useEffect?

3 months ago2 minutes read

There are many cases we need to return from useEffect.

We have to return a function from useEffect and that function will get called/executed when the component gets unmounted from the DOM.

Suppose you have ever started a counter using setInterval or made a connection to a WebSocket that continuously receives messages. In that case, might also want to not listen to the WebSocket or cancel the interval when the component gets unmounted. Because you no longer need the counter or receive messages from the WebSocket.

Let's see in action

jsimport React, { useState, useEffect }from 'react'

const Counter = () => {
  const [count, setCount] = useState(0)

  useEffect(() => {
    const interval = setInterval(() => {
      setCount(prev => prev + 1)
      
      console.log("Counting")
    }, 1000)
  })
  return (
    <div>Counter {count}</div>
  )
}

export default Counter

Normally when this component renders it will increase the count and the count will be shown in the DOM. And also print Counting on the console. But if we conditionally remove this component from DOM you will see it's still printing on the console.

To prevent this unnecessary print stop the interval we have to add a return function inside useEffect

jsuseEffect(() => {
    const interval = setInterval(() => {
      setCount(prev => prev + 1)
      
      console.log("Counting")
    }, 1000)

    return () => {
      clearInterval(interval)
    }
  })

Now it solves the problem

ShahriyarAlam

Copythight © All Rights Reserved.