October 2019
Intermediate to advanced
426 pages
11h 49m
English
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
Read now
Unlock full access