JavaScript and React course · Module 5: useEffect and Custom Hooks
Cleaning Up Effects
In this lesson10
Properly cleaning up side effects is a crucial aspect of building reliable React applications. Just as astronauts must maintain their life support systems to avoid malfunctions, we too must take care of cleaning up our effects to avoid memory leaks, unnecessary computations, and other problems.
Why is cleaning up effects important?
When a component is unmounted (removed from the DOM) or when effect dependencies change, various problems can occur if we don't take care of proper cleanup:
- Memory leaks - unused resources that are not released
- Updating state of unmounted components - leads to warnings and errors
- Unnecessary computations - consuming resources on operations that are no longer needed
- Conflicting updates - when old and new effects run simultaneously
- Ghost subscriptions - old subscriptions still responding to events
Basic cleanup function syntax
In useEffect, the cleanup function is returned from the effect function:
useEffect(() => {
// Effect code - runs after rendering
console.log('Effect triggered');
// Cleanup function - runs before the next effect or on unmount
return () => {
console.log('Effect cleaned up');
};
}, [dependency]); // Dependency arrayWhen is the cleanup function called?
The cleanup function is invoked in two situations:
- Before re-running the effect - when dependencies change
- Before the component unmounts - when the component is removed from the DOM
function SpaceModule({ moduleId }) {
useEffect(() => {
console.log(`Module ${moduleId} has been initialized`);
// This function will be called:
// 1. Before the next initialization when moduleId changes
// 2. When the SpaceModule component is unmounted
return () => {
console.log(`Module ${moduleId} has been shut down`);
};
}, [moduleId]);
return <div className="space-module">Space module: {moduleId}</div>;
}Common cases requiring cleanup
1. Intervals and timeouts
Unreleased intervals and timeouts can continue running in the background, consuming resources and potentially updating the state of components that no longer exist:
function Countdown({ seconds, onComplete }) {
const [timeLeft, setTimeLeft] = useState(seconds);
useEffect(() => {
// Don't start countdown if already finished
if (timeLeft <= 0) {
onComplete();
return;
}
console.log(`Starting the countdown from ${timeLeft}`);
// Setting up interval
const intervalId = setInterval(() => {
setTimeLeft(prevTime => {
if (prevTime <= 1) {
onComplete();
return 0;
}
return prevTime - 1;
});
}, 1000);
// Cleanup function stops the interval
return () => {
console.log(`Stopping countdown at ${timeLeft}`);
clearInterval(intervalId);
};
}, [timeLeft, onComplete]);
return <div className="countdown">{timeLeft}</div>;
}2. Subscriptions to external data sources
Subscriptions that are not cancelled can continue receiving data and causing state updates:
function TelemetryMonitor({ shipId }) {
const [data, setData] = useState(null);
useEffect(() => {
let isMounted = true;
console.log(`Started monitoring ship ${shipId}`);
// Creating telemetry subscription
const subscription = telemetryService.subscribe(shipId, telemetryData => {
// Update state only if component is still mounted
if (isMounted) {
setData(telemetryData);
}
});
// Cleanup function cancels the subscription
return () => {
console.log(`Stopping monitoring of ship ${shipId}`);
isMounted = false;
subscription.unsubscribe();
};
}, [shipId]);
if (!data) return <div>Waiting for telemetry data...</div>;
return (
<div className="telemetry">
<h3>Ship telemetry: {shipId}</h3>
<p>Oxygen level: {data.oxygen}%</p>
<p>Temperature: {data.temperature}°C</p>
<p>Velocity: {data.velocity} km/h</p>
</div>
);
}3. DOM event listeners
Event listeners that are not removed can lead to memory leaks:
function KeyboardShortcuts({ onEscape }) {
useEffect(() => {
console.log('Installing keyboard listener');
// Function handling key press
const handleKeyDown = (event) => {
if (event.key === 'Escape') {
onEscape();
}
};
// Adding listener to document
document.addEventListener('keydown', handleKeyDown);
// Cleanup function removes the listener
return () => {
console.log('Removing keyboard listener');
document.removeEventListener('keydown', handleKeyDown);
};
}, [onEscape]);
return null; // This component renders nothing visible
}4. WebSockets and real-time connections
Connections that remain open can consume resources and cause leaks:
function MissionControlSocket({ missionId, onMessage }) {
const [status, setStatus] = useState('disconnected');
useEffect(() => {
let socket = null;
// Function initializing connection
const connect = () => {
console.log(`Connecting to mission ${missionId}`);
setStatus('connecting');
// Creating WebSocket
socket = new WebSocket(`wss://mission-control.space/mission/${missionId}`);
socket.onopen = () => {
console.log(`Connected to mission ${missionId}`);
setStatus('connected');
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
onMessage(data);
};
socket.onerror = (error) => {
console.error(`WebSocket connection error: ${error.message}`);
setStatus('error');
};
socket.onclose = () => {
console.log(`Disconnected from mission ${missionId}`);
setStatus('disconnected');
};
};
// Initialize connection
connect();
// Cleanup function closes the connection
return () => {
console.log(`Closing connection to mission ${missionId}`);
if (socket) {
socket.close();
}
};
}, [missionId, onMessage]);
return (
<div className="socket-status">
Connection status: {status}
</div>
);
}5. Canceling fetch requests
Canceling ongoing fetch requests prevents state updates after unmounting:
function PlanetInfo({ planetId }) {
const [planet, setPlanet] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
// Creating controller to cancel request
const abortController = new AbortController();
const signal = abortController.signal;
async function fetchPlanetData() {
try {
setLoading(true);
console.log(`Fetching data for planet ${planetId}`);
const response = await fetch(`https://api.space.com/planets/${planetId}`, {
signal // pass signal to fetch
});
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
const data = await response.json();
setPlanet(data);
setError(null);
} catch (err) {
// Ignore cancellation errors
if (err.name !== 'AbortError') {
console.error(`Error fetching data: ${err.message}`);
setError(`Failed to fetch planet data: ${err.message}`);
}
} finally {
setLoading(false);
}
}
fetchPlanetData();
// Cleanup function cancels ongoing requests
return () => {
console.log(`Canceling request for planet ${planetId}`);
abortController.abort();
};
}, [planetId]);
if (loading) return <div>Loading planet data...</div>;
if (error) return <div>Error: {error}</div>;
if (!planet) return <div>No planet data</div>;
return (
<div className="planet-card">
<h2>{planet.name}</h2>
<p>Typ: {planet.type}</p>
<p>Diameter: {planet.diameter} km</p>
<p>Distance from Sun: {planet.distanceFromSun} million km</p>
</div>
);
}Advanced effect cleanup patterns
1. The isMounted flag
Although using AbortController is the preferred way to cancel fetch requests, in cases where we cannot easily cancel an asynchronous operation, we can use an isMounted flag:
function AsteroidTracker({ asteroidId }) {
const [data, setData] = useState(null);
useEffect(() => {
let isMounted = true; // Flag indicating whether component is mounted
async function fetchAsteroidData() {
const response = await fetch(`https://api.nasa.gov/neo/rest/v1/neo/${asteroidId}`);
const asteroidData = await response.json();
// Update state only if component is still mounted
if (isMounted) {
setData(asteroidData);
}
}
fetchAsteroidData();
// Cleanup function changes the flag
return () => {
isMounted = false;
};
}, [asteroidId]);
// Rendering...
}2. Synchronization with external state stores
When synchronizing React state with an external state store, it's important to restore the previous state during cleanup:
function ThemeSwitcher({ theme }) {
useEffect(() => {
// Save current theme
const previousTheme = document.body.dataset.theme;
// Set new theme
document.body.dataset.theme = theme;
console.log(`Changing theme to: ${theme}`);
// Restore previous theme during cleanup
return () => {
console.log(`Restoring previous theme: ${previousTheme || 'default'}`);
document.body.dataset.theme = previousTheme || 'default';
};
}, [theme]);
return (
<div className="theme-info">
Current theme: {theme}
</div>
);
}3. Handling shared resources
When multiple components share resources, a reference counting system should be used:
// Singleton for managing shared resources
class SharedResourceManager {
constructor() {
this.resources = new Map();
this.refCounts = new Map();
}
// Acquire resource (increment reference count)
acquire(resourceId, creator) {
if (!this.resources.has(resourceId)) {
// Create resource if it doesn't exist
this.resources.set(resourceId, creator());
this.refCounts.set(resourceId, 0);
}
// Increment reference count
this.refCounts.set(resourceId, this.refCounts.get(resourceId) + 1);
return this.resources.get(resourceId);
}
// Release resource (decrement reference count)
release(resourceId) {
if (!this.resources.has(resourceId)) return;
// Decrement reference count
const newCount = this.refCounts.get(resourceId) - 1;
this.refCounts.set(resourceId, newCount);
// Remove resource when no more references
if (newCount <= 0) {
const resource = this.resources.get(resourceId);
if (resource.dispose && typeof resource.dispose === 'function') {
resource.dispose();
}
this.resources.delete(resourceId);
this.refCounts.delete(resourceId);
}
}
}
// Singleton for use across the entire application
export const sharedResources = new SharedResourceManager();
// Hook for using shared resource
function useSharedResource(resourceId, createResource) {
useEffect(() => {
// Acquire resource
const resource = sharedResources.acquire(resourceId, createResource);
console.log(`Resource ${resourceId} acquired, number of users: ${sharedResources.refCounts.get(resourceId)}`);
// Release resource during cleanup
return () => {
sharedResources.release(resourceId);
console.log(`Resource ${resourceId} released`);
};
}, [resourceId]);
return sharedResources.resources.get(resourceId);
}
// Example usage
function SpaceshipScanner() {
// This resource will be shared between all component instances
const scanner = useSharedResource('advanced-scanner', () => {
console.log('Scanner initialization (expensive operation)');
return {
scan: (target) => console.log(`Scanning ${target}...`),
dispose: () => console.log('Shutting down scanner')
};
});
return (
<button onClick={() => scanner.scan('Mars')}>
Scan Mars
</button>
);
}Common problems and solutions
1. Stack overflow when cleaning up timers
Problem: Improperly stopping a timer can lead to stack overflow:
// BAD: Cleanup function doesn't stop the timeout properly
useEffect(() => {
function tick() {
setCount(count + 1);
setTimeout(tick, 1000);
}
tick();
return () => {
// Problem: we don't have a reference to the current timeout ID
};
}, [count]); // Dependency causes the effect to re-runSolution: Store the current timeout ID:
// GOOD: We save the timeout ID so we can cancel it
useEffect(() => {
let timeoutId = null;
function tick() {
setCount(prevCount => prevCount + 1);
timeoutId = setTimeout(tick, 1000);
}
timeoutId = setTimeout(tick, 1000);
return () => {
clearTimeout(timeoutId);
};
}, []); // No dependencies - we run only once2. Problems with cleanup ordering
Problem: Sometimes cleanup order matters, especially when we have several nested effects:
// Problematic cleanup order
useEffect(() => {
// Outer effect
const resource = initializeResource();
useEffect(() => {
// Inner effect using the resource
resource.use();
return () => {
// This cleanup may be called after the resource is released
resource.stopUsing();
};
}, [someCondition]);
return () => {
// This resource may already be in use by the inner effect
resource.dispose();
};
}, []);Solution: Use separate, independent effects:
// Better approach
useEffect(() => {
// Effect initializing resource
const resource = initializeResource();
return () => {
// Cleaning up resource
resource.dispose();
};
}, []);
useEffect(() => {
// Effect using resource (use useRef or context)
if (resourceRef.current) {
resourceRef.current.use();
return () => {
if (resourceRef.current) {
resourceRef.current.stopUsing();
}
};
}
}, [someCondition]);3. State inconsistency during cleanup
Problem: During cleanup we may access outdated state:
function SpaceshipControl({ shipId }) {
const [power, setPower] = useState(100);
useEffect(() => {
// Initializing ship control
const ship = spaceshipAPI.connect(shipId);
ship.setPower(power);
return () => {
// Problem: power may be stale during cleanup
console.log(`Disconnecting from ship at power: ${power}`);
ship.disconnect();
};
}, [shipId]); // No dependency on power
return (
<div>
<p>Engine power: {power}%</p>
<button onClick={() => setPower(power - 10)}>Reduce power</button>
</div>
);
}Solution: Use references to store current state values:
function SpaceshipControl({ shipId }) {
const [power, setPower] = useState(100);
const powerRef = useRef(power);
// Updating reference on every state change
useEffect(() => {
powerRef.current = power;
}, [power]);
useEffect(() => {
// Initializing ship control
const ship = spaceshipAPI.connect(shipId);
ship.setPower(power);
return () => {
// We use the current value from the ref
console.log(`Disconnecting from ship at power: ${powerRef.current}%`);
ship.disconnect();
};
}, [shipId, power]);
return (
<div>
<p>Engine power: {power}%</p>
<button onClick={() => setPower(power - 10)}>Reduce power</button>
</div>
);
}Testing effect cleanup
To ensure that effects are properly cleaned up, it's worth writing tests that verify this behavior:
// Example test for a component with effect cleanup
import { render, act, screen } from '@testing-library/react';
import { useState } from 'react';
// Simple component with timer for testing
function TimerComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setCount(c => c + 1);
}, 100);
return () => clearInterval(interval);
}, []);
return <div data-testid="count">{count}</div>;
}
// Effect cleanup test
test('effect cleanup stops the interval', async () => {
jest.useFakeTimers();
const { unmount } = render(<TimerComponent />);
// Allow a few timer ticks
act(() => {
jest.advanceTimersByTime(250);
});
const countBefore = Number(screen.getByTestId('count').textContent);
// Unmount component (should clean up effect and stop timer)
unmount();
// Advance clock forward once more
act(() => {
jest.advanceTimersByTime(250);
});
// Since component is unmounted and timer stopped,
// we can only check that counter didn't grow too much before unmounting
expect(countBefore).toBeGreaterThanOrEqual(2);
expect(countBefore).toBeLessThanOrEqual(3);
jest.useRealTimers();
});Best practices for cleaning up effects
Always clean up effects that create subscriptions - timers, event listeners, WebSocket connections, etc.
Use AbortController to cancel fetch requests - it's the standard mechanism for canceling asynchronous operations.
Maintain a mounting flag - for asynchronous operations that cannot be cancelled, use an
isMountedflag and check it before updating state.Store references to resources - local variables in an effect cease to exist after cleanup, so use
useRefto store resource references.Avoid overly complex effects - an effect that does too many things will be harder to clean up properly. Consider splitting it into smaller, more focused effects.
Avoid async cleanup functions - cleanup functions should be synchronous so React can guarantee their execution in the proper order.
Test effect cleanup - it's especially important to test unmounting components that create external subscriptions.
Effect Cleanup and Performance
Proper effect cleanup not only prevents memory leaks but can also significantly impact application performance:
Lower memory usage - by releasing unused resources
Fewer unnecessary computations - by canceling operations that are no longer needed
Reduced number of re-renders - by avoiding unnecessary state updates
Faster page reloads - by ensuring all resources are properly released
Summary
Cleaning up effects is an often overlooked but crucial aspect of working with React. Just as astronauts must take care of their life support systems, developers must take care of cleaning up their side effects.
Well-written cleanup functions:
- Prevent memory leaks
- Avoid updating state of unmounted components
- Release system resources
- Ensure application consistency
Remember that every effect that creates a connection, subscription, or reserves resources should also release them during cleanup.
Code for this lesson: App.jsx
import React, { useState, useEffect } from 'react';
// Demonstrating cleanup with timers
function TimerWithCleanup() {
const [count, setCount] = useState(0);
const [isRunning, setIsRunning] = useState(false);
useEffect(() => {
if (!isRunning) return;
console.log('⏰ Timer started');
const interval = setInterval(() => {
setCount(c => c + 1);
}, 1000);
// CLEANUP - very important!
return () => {
console.log('Timer stopped (cleanup)');
clearInterval(interval);
};
}, [isRunning]);
return (
<div className="demo-card">
<h2>⏱Timer with Cleanup</h2>
<div className="counter">{count}s</div>
<div className="controls">
<button onClick={() => setIsRunning(true)} disabled={isRunning}>
▶Start
</button>
<button onClick={() => setIsRunning(false)} disabled={!isRunning}>
⏹Stop
</button>
<button onClick={() => { setCount(0); setIsRunning(false); }}>
Reset
</button>
</div>
<p className="hint">Open the console to see cleanup logs</p>
</div>
);
}
// Demonstrating cleanup with event listeners
function MouseTrackerWithCleanup() {
const [position, setPosition] = useState({ x: 0, y: 0 });
const [tracking, setTracking] = useState(false);
useEffect(() => {
if (!tracking) return;
const handleMouseMove = (e) => {
setPosition({ x: e.clientX, y: e.clientY });
};
console.log('Mouse tracking enabled');
window.addEventListener('mousemove', handleMouseMove);
// CLEANUP - removing the event listener
return () => {
console.log('Mouse tracking disabled (cleanup)');
window.removeEventListener('mousemove', handleMouseMove);
};
}, [tracking]);
return (
<div className="demo-card">
<h2>Mouse Tracking</h2>
<div className="position">
X: {position.x} | Y: {position.y}
</div>
<button onClick={() => setTracking(!tracking)}>
{tracking ? 'Disable tracking' : 'Enable tracking'}
</button>
<p className="hint">
{tracking ? 'Move your mouse!' : 'Click to enable'}
</p>
</div>
);
}
// Demonstrating cleanup with subscriptions
function SubscriptionWithCleanup() {
const [messages, setMessages] = useState([]);
const [subscribed, setSubscribed] = useState(false);
useEffect(() => {
if (!subscribed) return;
console.log('Subscribed to space channel');
// Simulating a subscription (e.g. WebSocket)
const interval = setInterval(() => {
const newMessage = {
id: Date.now(),
text: `Transmission #${Math.floor(Math.random() * 1000)}`,
time: new Date().toLocaleTimeString()
};
setMessages(prev => [...prev.slice(-4), newMessage]);
}, 2000);
// CLEANUP - canceling the subscription
return () => {
console.log('Unsubscribed from space channel (cleanup)');
clearInterval(interval);
};
}, [subscribed]);
return (
<div className="demo-card">
<h2>Subscription</h2>
<div className="messages">
{messages.length === 0 ? (
<p className="empty">No messages</p>
) : (
messages.map(msg => (
<div key={msg.id} className="message">
[{msg.time}] {msg.text}
</div>
))
)}
</div>
<button onClick={() => {
setSubscribed(!subscribed);
if (subscribed) setMessages([]);
}}>
{subscribed ? 'Cancel subscription' : 'Subscribe'}
</button>
</div>
);
}
// Component showing a memory leak problem
function MemoryLeakDemo() {
const [showChild, setShowChild] = useState(true);
const [logs, setLogs] = useState([]);
const addLog = (msg) => setLogs(prev => [...prev.slice(-5), msg]);
return (
<div className="demo-card wide">
<h2>Memory Leak Demo</h2>
<button onClick={() => {
setShowChild(!showChild);
addLog(showChild ? 'Component unmounted' : 'Component mounted');
}}>
{showChild ? 'Unmount component' : 'Mount component'}
</button>
<div className="child-container">
{showChild && <ChildWithCleanup onLog={addLog} />}
</div>
<div className="logs">
<h3>Logs:</h3>
{logs.map((log, i) => <div key={i}>{log}</div>)}
</div>
</div>
);
}
function ChildWithCleanup({ onLog }) {
useEffect(() => {
onLog('Effect started');
const timer = setInterval(() => {
onLog('⏰ Timer tick');
}, 2000);
return () => {
onLog('Cleanup performed - timer cleared');
clearInterval(timer);
};
}, []);
return <div className="child">Child component (with effect)</div>;
}
function App() {
return (
<div className="app">
<h1>Cleaning Up Effects (Cleanup)</h1>
<p className="subtitle">Managing resources in useEffect</p>
<div className="demos">
<TimerWithCleanup />
<MouseTrackerWithCleanup />
<SubscriptionWithCleanup />
<MemoryLeakDemo />
</div>
</div>
);
}
export default App;Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is the best way to organize multiple effects in a component?
2. How do you properly handle errors in asynchronous operations within useEffect?
Hands-on tasks in the game
- Horizontal ordering
Arrange the cleanup syntax elements in useEffect from left to right:
- Code editor
LocalStorage Settings Sync
- Click in order
Arrange the useEffect syntax with a cleanup function:
- Vertical ordering
Order advanced useEffect patterns from basic to complex:
- Code editor
Intersection Observer for Lazy Loading