MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Cleanup Functions in useEffect0%
Study Materials
React.js for BeginnersProgress 0%
1.1Why React and Single-Page Architecture1.2Setting Up Modern React with Vite1.3React Project Directory Structure and Entry Points1.4Virtual DOM and React Render Cycle Explained
8.1Rules of React Hooks8.2The useEffect Hook for Side Effects8.3The Dependency Array and Execution Lifecycle8.4Cleanup Functions in useEffect
HomeTutorialsReact.js for BeginnersCleanup Functions in useEffect
Inline Styles and Style Objects

Cleanup Functions in useEffect

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

1. Why Cleanup Is Essential

Not all side effects are "fire-and-forget". Many side effects establish connections, timers, or event listeners that will cause serious memory leaks, duplicated callbacks, or state updates on unmounted components if not properly disassembled when the component disappears:

  • Timers: setInterval, setTimeout
  • Subscriptions: WebSockets, Firebase real-time listeners, Chat services
  • DOM Event Listeners: window.addEventListener('resize', ...)
  • Abortable Fetch Requests: AbortController

To clean up after side effects, return a cleanup function from your useEffect callback.

1Component Mounts:
2[Setup Effect Executes] (e.g. window.addEventListener('resize', handleResize))
3 
4Component Updates (or Unmounts):
5[Cleanup Function Executes First!] (e.g. window.removeEventListener('resize', handleResize))
6[New Setup Effect Executes]

2. Example: Window Resize Listener

1import React, { useState, useEffect } from 'react';
2 
3export default function WindowDimensions() {
4 const [width, setWidth] = useState(window.innerWidth);
5 
6 useEffect(() => {
7 const handleResize = () => setWidth(window.innerWidth);
8 
9 // 1. Setup: Attach listener
10 window.addEventListener('resize', handleResize);
11 console.log('Event listener registered');
12 
13 // 2. Cleanup: Return function to remove listener
14 return () => {
15 window.removeEventListener('resize', handleResize);
16 console.log('Event listener cleaned up');
17 };
18 }, []); // Run on mount, clean up on unmount
19 
20 return <p>Window width: {width}px</p>;
21}

3. Example: Timer with setInterval

1import React, { useState, useEffect } from 'react';
2 
3export default function ExamTimer({ initialMinutes = 30 }) {
4 const [secondsLeft, setSecondsLeft] = useState(initialMinutes * 60);
5 
6 useEffect(() => {
7 // 1. Setup interval
8 const timerId = setInterval(() => {
9 setSecondsLeft((prev) => (prev > 0 ? prev - 1 : 0));
10 }, 1000);
11 
12 // 2. Cleanup interval
13 return () => clearInterval(timerId);
14 }, []);
15 
16 return (
17 <div className="timer-badge">
18 Time Remaining: {Math.floor(secondsLeft / 60)}m {secondsLeft % 60}s
19 </div>
20 );
21}

If you omit clearInterval(timerId), the timer will keep running in the background forever—even after the user navigates to a completely different page—leaking memory and triggering phantom state updates.

4. Canceling Network Requests with AbortController

If a user rapidly toggles between different tabs or pages, an earlier API request might finish after the component has already unmounted. Use standard browser AbortController to cancel in-flight requests:

1useEffect(() => {
2 const controller = new AbortController();
3 
4 async function fetchUserData() {
5 try {
6 const response = await fetch(`/api/user/${userId}`, {
7 signal: controller.signal
8 });
9 const data = await response.json();
10 setUser(data);
11 } catch (err) {
12 if (err.name !== 'AbortError') {
13 console.error('Fetch error:', err);
14 }
15 }
16 }
17 
18 fetchUserData();
19 
20 // Cleanup: Abort fetch if userId changes or component unmounts
21 return () => controller.abort();
22}, [userId]);

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
How do you declare a cleanup function inside useEffect?
Question 2
What severe issue occurs if an active setInterval timer is created in useEffect without a cleanup function?
Question 3
When does React execute the cleanup function?
Question 4
Which native browser API is used to abort in-flight fetch requests inside a useEffect cleanup function?
Question 5
Why does <React.StrictMode> run effect setup and cleanup twice during development?
Next Lesson

Inline Styles and Style Objects

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
The Dependency Array and Execution LifecycleInline Styles and Style Objects

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Beginners with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext