Cleaning up effects

Sometimes effects need to be cleaned up when the component unmounts. To do so, we can return a function from the effect function of the Effect Hook. This returned function works similarly to the componentWillUnmount life cycle method:

    useEffect(() => {
const updateInterval = setInterval(() => console.log('fetching update'), updateTime)

return () => clearInterval(updateInterval)
}, [updateTime])

The code marked in bold above is called the cleanup function. The cleanup function will be called when the component unmounts and before running the effect again. This avoids bugs when, for example, the updateTime prop changes. In that case, the previous effect will be cleaned up and a new interval with the updated updateTime value will be defined.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.104.29