0

I understand that useEffect() hook replaces componentDidUpdate(), componentDidMount(), componentWillUnmount() so it gets called in place of each of those 3 methods.

So in my code I have: (There is a timer that increments for each second in the document)

useEffect(()=>{

 const intervalId = setInterval(()=>{
  setTime((prevTime) => prevTime + 1)
 },1000)

 // return ()=>{
 //   clearInterval(intervalId)
 // }

},[])

As far as I understand, having an empty array as 2nd parameter makes useEffect no to be called for componentDidUpdate(), so it will be called for the other two methods.

Want I don't grasp is why useEffect isn't called when componentWillUnmount() - which I think is the moment right before the component is updated with the new timer.

In the end why it works in the same manner even I uncomment/comment the clearInterval() part?

Thanks!

Alex Barbu
  • 87
  • 1
  • 7

1 Answers1

0

The method your useEffect returns clearInterval(intervalId) is where you want to have the code that you would put in componentWillUnmount(). For cleanup.

useEffect is not called as an equal to componentWillUnmount() in an lifecycle sense, only the method it returns is.