upvote

0

downvote

0

save

What is React’s useEffect cleanup function for?

clock icon

asked 403 days ago

message icon

1

eye icon

7

I know useEffect hooks can return a cleanup function, but I’m not sure when to use it. Can someone explain what it does and give an example?

1 Answer

The cleanup function runs before the next effect (or on unmount). It’s used to tear down subscriptions, timers, or event listeners:

1CopyEditimport { useEffect } from 'react';
2
3function Component() {
4 useEffect(() => {
5 const intervalId = setInterval(() => {
6 console.log('tick');
7 }, 1000);
8
9 // Cleanup runs on unmount or before next effect
10 return () => {
11 clearInterval(intervalId);
12 };
13 }, []); // empty deps: runs once, cleanup on unmount
14
15 return <div>Check the console</div>;
16}
17
1CopyEditimport { useEffect } from 'react';
2
3function Component() {
4 useEffect(() => {
5 const intervalId = setInterval(() => {
6 console.log('tick');
7 }, 1000);
8
9 // Cleanup runs on unmount or before next effect
10 return () => {
11 clearInterval(intervalId);
12 };
13 }, []); // empty deps: runs once, cleanup on unmount
14
15 return <div>Check the console</div>;
16}
17

Without cleanup, the interval would keep running even after your component is gone, causing memory leaks.

1

Write your answer here

Top Questions