From the course: Build Modern Web Apps with React, Hooks, State Management, and APIs Using Vite or Next.js

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

useEffect cleanup function and summary

useEffect cleanup function and summary

Welcome back, now let's discuss another very important topic with useEffect i.e. cleanup function. Cleanup functions are very important as not having it, you can have memory leaks in the system. So it helps prevent memory leaks. It runs on the unmount of your component before running the effect. This is an example of a cleanup function with useEffect. This is one common example that where your cleanup should be happening or you might be doing cleanup in other cases as well. Over here we have a timer defined which has a set interval of 1000 milliseconds and on every second it's going to run a console.log of tick. Now for example, you leave that component out and you do not have a cleanup function defined here like below. Inside your use effect, you have to define the cleanup function. Over here you are calling the clear interval function and clearing your timer and the console.log of cleanup is going to run once upon your components unmount. This is very important as it prevents memory…

Contents