Cleanup Functions in React JS
Cleanup Functions are an important part of React JS that help developers remove event listeners, stop timers, cancel subscriptions, disconnect external connections, and prevent unwanted side effects when a component updates or unmounts. Cleanup functions are commonly returned from the useEffect() Hook.
Understanding cleanup functions helps developers create reliable, efficient, and maintainable React applications.
React JS Training: Explore JustAcademy React JS Training
Course Demo: Register for React JS Course Demo
1. What Is a Cleanup Function in React?
A cleanup function is an optional function returned by an Effect's setup function. React uses it to undo or stop the work performed by the previous Effect setup when the Effect needs to run again or when the component is removed from the screen.
Cleanup functions are especially useful when a component interacts with external systems, including browser events, timers, subscriptions, WebSocket connections, and third-party libraries.
Basic Syntax
import { useEffect } from "react";
function Example() {
useEffect(() => {
// Setup logic
console.log("Effect started");
return () => {
// Cleanup logic
console.log("Effect cleaned up");
};
}, []);
return <h1>Cleanup Function Example</h1>;
}
export default Example;
Explanation:
useEffect() declares an Effect inside a function component.
- The setup function contains the work that needs to be performed.
- The returned function contains the cleanup logic.
- React runs cleanup before the Effect runs again with changed dependencies.
- React also runs cleanup when the component unmounts.
2. Why Are Cleanup Functions Important?
React components may create resources that continue working outside React's rendering process. If these resources are not released when necessary, they can cause duplicate event handlers, unnecessary network activity, incorrect behavior, or memory and performance problems.
Cleanup functions help developers:
- Prevent duplicate event listeners.
- Stop intervals and timeouts when they are no longer needed.
- Unsubscribe from external data sources.
- Disconnect WebSocket or chat connections.
- Cancel supported asynchronous operations.
- Prevent outdated asynchronous responses from updating component state.
- Keep component behavior predictable during updates and unmounting.
3. When Does a Cleanup Function Execute?
A cleanup function can execute at different points depending on the component's lifecycle and the Effect's dependencies.
3.1 Before an Effect Runs Again
When one or more dependencies change, React runs the cleanup from the previous Effect setup before running the new setup after the updated commit.
3.2 When a Component Unmounts
When React removes a component from the UI, it runs the final cleanup for its active Effects.
3.3 During Development Strict Mode
When React Strict Mode is enabled, React performs an additional development-only setup-and-cleanup cycle before the initial real setup. This helps identify Effects whose cleanup does not correctly undo their setup.
Lifecycle Sequence
Component renders
|
v
React commits the UI
|
v
Effect setup executes
|
v
Dependencies change?
|
+---- Yes ----> Previous cleanup executes
| |
| v
| New Effect setup
|
+---- No ----> Effect remains active
|
v
Component unmounts
|
v
Final cleanup executes
4. Cleanup Functions with setInterval()
The setInterval() function repeatedly executes a callback after a specified time interval. When the component no longer needs the timer, the interval should be stopped using clearInterval().
Example
import { useEffect, useState } from "react";
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => {
setSeconds(previous => previous + 1);
}, 1000);
return () => {
clearInterval(intervalId);
};
}, []);
return <h2>Seconds: {seconds}</h2>;
}
export default Timer;
Explanation
- The Effect starts a timer after the initial client-side commit.
- The timer increments the seconds value every second.
- The state update causes React to render the updated counter.
- The empty dependency array prevents ordinary re-renders from restarting the Effect.
- When the component unmounts, the cleanup stops the timer.
Important: Using the functional state update previous => previous + 1 avoids depending on a captured count value and helps keep the interval stable.
5. Cleanup Functions with setTimeout()
The setTimeout() function schedules a callback to execute after a delay. If the component is removed or the scheduled action is no longer needed, use clearTimeout() to cancel it.
Example
import { useEffect, useState } from "react";
function Notification() {
const [message, setMessage] = useState("Loading...");
useEffect(() => {
const timeoutId = setTimeout(() => {
setMessage("Welcome to React JS!");
}, 2000);
return () => {
clearTimeout(timeoutId);
};
}, []);
return <p>{message}</p>;
}
export default Notification;
Explanation: The message changes after two seconds. If the component unmounts before the timeout fires, the cleanup cancels the scheduled callback.
6. Cleanup Functions with Event Listeners
Event listeners allow a component to respond to browser events such as resizing the window, scrolling, or pressing keyboard keys. When an event listener is no longer required, remove it using removeEventListener().
Example: Window Resize Listener
import { useEffect, useState } from "react";
function WindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
}, []);
return <h2>Window Width: {width}px</h2>;
}
export default WindowWidth;
Explanation
- The component reads the current window width.
- The Effect registers a resize listener.
- When the browser window changes size, the listener updates the state.
- The cleanup removes the same listener using the same callback reference.
- Removing the listener prevents it from remaining registered after the component unmounts.
Note: This example assumes a browser environment. In server-rendered applications, access to window must be handled carefully because it is unavailable during server rendering.
7. Cleanup Functions with API Requests
When an Effect starts an API request, the component may unmount or its dependencies may change before the request finishes. Cleanup can abort a supported request with AbortController or prevent an outdated response from being used.
Example: Aborting an API Request
import { useEffect, useState } from "react";
function Users() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
async function fetchUsers() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users",
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error("Failed to fetch users");
}
const data = await response.json();
setUsers(data);
} catch (err) {
if (err.name !== "AbortError") {
setError(err.message);
}
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
fetchUsers();
return () => controller.abort();
}, []);
if (loading) return <p>Loading users...</p>;
if (error) return <p>Error: {error}</p>;
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
export default Users;
Explanation
- The Effect creates an
AbortController.
- The controller's signal is passed to
fetch().
- If cleanup runs before the request completes,
controller.abort() requests cancellation.
- The error handler ignores the expected abort error.
- The loading state is not changed by the request's
finally block if the request has been aborted.
Important: Aborting a request does not reverse a request that has already completed on the server. For asynchronous operations that cannot be cancelled, use an appropriate stale-result or ignore flag to prevent outdated results from being applied.
8. Cleanup Functions with Event Subscriptions
Applications often subscribe to data sources that notify a component when information changes. When the subscription is no longer needed, the component should unsubscribe.
Example
import { useEffect, useState } from "react";
function OnlineStatus({ statusSource }) {
const [isOnline, setIsOnline] = useState(false);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status);
}
statusSource.subscribe(handleStatusChange);
return () => {
statusSource.unsubscribe(handleStatusChange);
};
}, [statusSource]);
return (
<p>Status: {isOnline ? "Online" : "Offline"}</p>
);
}
export default OnlineStatus;
Explanation: The Effect subscribes to the supplied status source. When the source changes, React cleans up the old subscription before establishing the new one. When the component unmounts, the subscription is removed.
The example assumes that statusSource implements compatible subscribe() and unsubscribe() methods.
9. Cleanup Functions with WebSocket Connections
WebSockets enable real-time communication between a browser and a server. When a component opens a connection, it should close that connection when it is no longer needed.
Example
import { useEffect, useState } from "react";
function ChatConnection({ url }) {
const [status, setStatus] = useState("Connecting...");
useEffect(() => {
const socket = new WebSocket(url);
function handleOpen() {
setStatus("Connected");
}
function handleClose() {
setStatus("Disconnected");
}
socket.addEventListener("open", handleOpen);
socket.addEventListener("close", handleClose);
return () => {
socket.removeEventListener("open", handleOpen);
socket.removeEventListener("close", handleClose);
socket.close();
};
}, [url]);
return <p>Connection status: {status}</p>;
}
export default ChatConnection;
Explanation:
- The Effect creates a WebSocket connection.
- The open and close events update the displayed connection status.
- If the URL changes, cleanup removes the registered event listeners and closes the old connection before the new setup.
- When the component unmounts, cleanup closes the connection.
10. Cleanup Functions and Dependency Arrays
Dependency arrays determine when an Effect setup must run again. Cleanup is directly connected to this behavior.
| Dependency Pattern |
Cleanup Behavior |
| No dependency array |
Cleanup runs before the Effect setup on each subsequent committed render and when the component unmounts. |
Empty array [] |
Cleanup runs when the component unmounts, apart from the extra development Strict Mode setup-and-cleanup cycle. |
Dependencies [value] |
Cleanup runs before the Effect setup when a dependency changes and when the component unmounts. |
Example With Dependencies
import { useEffect } from "react";
function ChatRoom({ roomId }) {
useEffect(() => {
console.log("Connecting to room:", roomId);
return () => {
console.log("Disconnecting from room:", roomId);
};
}, [roomId]);
return <h2>Chat Room: {roomId}</h2>;
}
export default ChatRoom;
When roomId changes, the cleanup uses the previous Effect's captured room ID, then the new setup uses the latest room ID.
11. Cleanup Functions and React Strict Mode
React Strict Mode is a development tool that helps identify potential bugs. When enabled, React performs an additional setup-and-cleanup cycle for Effects during initial mounting.
Example
import { useEffect } from "react";
function Example() {
useEffect(() => {
console.log("Setup executed");
return () => {
console.log("Cleanup executed");
};
}, []);
return <h1>Strict Mode Example</h1>;
}
export default Example;
In development Strict Mode, the console may show a sequence similar to:
Setup executed
Cleanup executed
Setup executed
Explanation: This additional cycle helps verify that cleanup correctly undoes the setup. It is not a reason to disable cleanup or introduce a flag simply to prevent the second setup. The Effect should work correctly even when React repeats the setup-and-cleanup sequence.
12. Common Mistakes When Using Cleanup Functions
- Forgetting to clear timers: Intervals or timeouts may continue running when they are no longer needed.
- Removing the wrong event listener: Use the same event type and callback reference that were registered.
- Forgetting to unsubscribe: External sources may continue notifying a component unnecessarily.
- Closing a shared connection incorrectly: Ensure the component is responsible for the resource it closes.
- Ignoring dependency changes: A new setup may be needed when props or state used by the Effect change.
- Assuming cleanup only runs on unmount: React also runs cleanup before re-running an Effect with changed dependencies.
- Ignoring asynchronous race conditions: A request that cannot be cancelled may still finish after a newer request.
- Using cleanup for unrelated logic: Cleanup should reverse or stop the work performed by the corresponding setup.
13. Best Practices for Cleanup Functions
- Keep setup and cleanup logic together inside the same Effect.
- Return cleanup functions when the Effect creates resources that need to be released.
- Clear intervals with
clearInterval() and timeouts with clearTimeout().
- Remove browser event listeners with
removeEventListener().
- Unsubscribe from external subscriptions when they are no longer needed.
- Close WebSocket connections and other resources that the component owns.
- Use
AbortController when supported asynchronous requests should be cancelled.
- Include all required reactive values in the dependency array.
- Test Effects with React Strict Mode enabled.
- Avoid adding Effects when the task can be handled by ordinary rendering logic or an event handler.
14. Practical Example: Complete Cleanup Demonstration
import { useEffect, useState } from "react";
function CleanupDemo() {
const [count, setCount] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => {
setCount(previous => previous + 1);
}, 1000);
console.log("Timer started");
return () => {
clearInterval(intervalId);
console.log("Timer stopped");
};
}, []);
return (
<div>
<h1>Cleanup Function Demo</h1>
<p>Count: {count}</p>
</div>
);
}
export default CleanupDemo;
Expected Behavior
- The component mounts and the Effect starts an interval.
- The counter increases every second.
- React renders the updated count.
- The interval continues without being restarted on every render.
- When the component unmounts, the cleanup stops the interval.
15. Interview Questions and Answers
Q1. What is a cleanup function in React?
A cleanup function is an optional function returned from an Effect setup to undo or stop its work when the Effect needs to re-run or the component unmounts.
Q2. Why do we use cleanup functions?
They help release resources, prevent duplicate listeners, stop timers, unsubscribe from data sources, and cancel supported asynchronous operations.
Q3. When does a cleanup function execute?
It runs before the next setup when dependencies change and when the component unmounts. Development Strict Mode can also trigger an extra setup-and-cleanup cycle.
Q4. How do you stop a timer in React?
Use clearInterval() for an interval or clearTimeout() for a timeout inside the cleanup function.
Q5. How do you remove an event listener?
Use removeEventListener() with the same event type and callback reference used when registering the listener.
Q6. What happens if a cleanup function is missing?
If an Effect creates a resource that needs explicit release, that resource may continue operating unnecessarily or cause duplicate behavior. Not every Effect requires cleanup.
Q7. Does cleanup run before every render?
No. Cleanup runs before the Effect setup is repeated because dependencies changed, and when the component unmounts. If there is no dependency array, the Effect setup runs after every commit, so its previous cleanup runs before each subsequent setup.
Q8. How does cleanup work with API requests?
Cleanup can abort supported requests using AbortController or prevent stale responses from being applied by using an appropriate ignore flag.
16. Quick Revision Checklist
- Understand the purpose of cleanup functions.
- Know when React executes cleanup.
- Practice clearing intervals and timeouts.
- Learn how to remove event listeners.
- Understand subscription and WebSocket cleanup.
- Practice aborting API requests.
- Understand dependency arrays and cleanup behavior.
- Know how React Strict Mode tests Effect cleanup.
- Keep cleanup logic symmetrical with Effect setup.
17. Conclusion
Cleanup functions are essential when a React Effect creates resources or synchronizes with external systems. They help stop timers, remove event listeners, unsubscribe from external sources, close connections, and manage asynchronous operations. By writing cleanup logic that correctly reverses the corresponding setup, developers can build React applications that are more reliable, efficient, and easier to maintain.
Learn React JS with JustAcademy
Strengthen your understanding of React Hooks, component lifecycle, Effect dependencies, and cleanup functions through structured training and practical projects.
Explore JustAcademy React JS Training Course
Register for a React JS Course Demo