Hello! In our last lesson, we explored how the useEffect dependency array gives you precise control over when your side effects run. You learned to prevent infinite loops by managing dependencies and to handle state updates using the functional update form.
Today, we'll build on that knowledge to show how useEffect can be used to replicate the traditional lifecycle events of a component: mounting, updating, and unmounting. While modern React encourages thinking in terms of "synchronization" rather than lifecycles, understanding this mapping provides a powerful mental model, especially given your background with more classical object-oriented or procedural programming structures. This lesson will connect the behavior of useEffect to these three fundamental phases of a component's existence.
By the end of this lesson, you will be able to use different useEffect patterns to reliably run code when a component first appears, when it updates, and right before it disappears.
1. The Three Phases of a Component's Life
Before we map useEffect to them, let's quickly solidify our understanding of the three main stages in a React component's lifecycle.
- Mounting: The component is being created and inserted into the DOM for the first time. This is its "birth."
- Updating: The component is re-rendering because its props or state have changed. This can happen multiple times during its life.
- Unmounting: The component is being removed from the DOM. This is its "end."
The following video provides an excellent high-level overview of these three phases and what happens in each one.
The React Lifecycle: Simply Explained!
Watch this segment from 'The React Lifecycle: Simply Explained!' by Cosden Solutions to get a clear visual model of the mounting, updating, and unmounting phases.
Please watch from 04:05 to 23:06. This covers: The three main stages: Initial Render (Mount), Update, and Exit (Unmount). What happens during the initial mount phase (code runs, values initialize, JSX renders, useEffect is scheduled). The update phase, where values are recomputed and the DOM is updated. The unmount phase, where resources are released and cleanup happens.
While the video gives a great conceptual tour, the official React documentation frames this slightly differently, which may appeal to your computer science background. It describes a Trigger -> Render -> Commit cycle. A state or prop change triggers a re-render. React then renders the component (calls your function) to calculate the new UI snapshot (the Virtual DOM). Finally, it commits these changes to the actual DOM. useEffect runs after the commit phase.
2. Replicating componentDidMount
This happens when the component is added to the screen.
You've already learned the pattern for this: an effect with an empty dependency array ([]). Because the dependencies will never change, React runs the effect once after the initial render and never again. This is the direct functional equivalent of the componentDidMount lifecycle method in older class-based components.
Use Case: Initial data fetching, setting up subscriptions, or initializing a third-party library that needs a DOM element.
import { useState, useEffect } from 'react';
function Logger() {
useEffect(() => {
// This runs only once, after the component mounts.
console.log('Logger component has mounted!');
}, []); // Empty dependency array
return <div>Check the console.</div>;
}
This behavior is foundational. The React documentation explains it as an effect that connects to a system and then never needs to re-synchronize because its dependencies (of which there are none) never change.
The official React documentation discusses this pattern. This section explains why an effect with empty dependencies runs only on mount and unmount.
Read the section titled 'What an Effect with empty dependencies means'. It confirms that this pattern makes the effect run only when the component mounts and cleans up when it unmounts.
3. Replicating componentWillUnmount and Introducing the Cleanup Function
This happens right before the component is removed from the screen.
To run code when a component unmounts, you must return a function from your useEffect callback. This is called the cleanup function.
useEffect(() => {
// Effect logic runs on mount
console.log('Effect is active.');
// Cleanup function is returned
return () => {
// This runs on unmount
console.log('Cleaning up the effect before unmount.');
};
}, []); // Empty dependency array ensures cleanup is ONLY for unmounting
When the component is removed from the DOM, React will execute this cleanup function.
Use Case: Tearing down subscriptions, clearing timers (clearInterval), or removing event listeners to prevent memory leaks.
Let's look at a practical example. We'll create a component and then use a button to unmount it, watching the console for our logs.
import { useState, useEffect } from 'react';
function Timer() {
useEffect(() => {
const timerId = setInterval(() => {
console.log('Timer tick...');
}, 1000);
console.log('Timer component mounted and interval started.');
// This cleanup function is key!
return () => {
clearInterval(timerId);
console.log('Timer component unmounted and interval cleared.');
};
}, []);
return <div>I'm a timer. Open the console and then click "Toggle Timer".</div>;
}
export default function App() {
const [showTimer, setShowTimer] = useState(true);
return (
<div>
<button onClick={() => setShowTimer(prev => !prev)}>
Toggle Timer
</button>
{showTimer && <Timer />}
</div>
);
}
When you first load this, you'll see "Timer component mounted...". When you click "Toggle Timer", the Timer component unmounts, and you'll immediately see "Timer component unmounted...". If we didn't clear the interval, it would continue running in the background forever, causing a memory leak.
This video explicitly connects this pattern to the old componentWillUnmount method.
Learn React Hooks: useEffect - Simply Explained!
The video 'Learn React Hooks: useEffect - Simply Explained!' demonstrates exactly how the return function acts as the unmount cleanup.
Watch from 12:35 to 13:24. The narrator clearly states that with an empty dependency array, the cleanup function runs on unmount and is the functional equivalent of componentWillUnmount.
4. Replicating componentDidUpdate
This happens when the component re-renders due to a change in its props or state.
This is where the populated dependency array shines. An effect with dependencies runs after the initial mount, and then re-runs after any render where one of its dependencies has changed.
This is analogous to componentDidUpdate, but more efficient. In class components, you'd write:componentDidUpdate(prevProps) { if (prevProps.someId !== this.props.someId) { // do something } }
With useEffect, the dependency array [someId] handles that if check for you.
Here's the critical nuance: When an update triggers an effect to re-run, React first runs the cleanup function from the previous render, and then runs the effect function for the current render.
This cleanup-then-rerun cycle is fundamental. It ensures that you're always tearing down the old effect before setting up the new one, preventing duplicate subscriptions or other issues.
Think of it as synchronization:
- Stop synchronizing with the old state/props (run cleanup).
- Start synchronizing with the new state/props (run effect).
The following video demonstrates this perfectly using console.log.
Learn React Hooks: useEffect - Simply Explained!
Let's return to the 'useEffect - Simply Explained!' video. The presenter adds a console.log to the cleanup function to show exactly when it runs during an update.
Watch from 09:17 to 11:51. Notice the order of the logs when the state is updated. You'll see 'I am being cleaned up' before the new 'The count is...' log. This demonstrates the cleanup-then-rerun cycle.
Let's see this in a code example that reacts to a prop change.
import { useState, useEffect } from 'react';
interface UserProfileProps {
userId: number;
}
function UserProfile({ userId }: UserProfileProps) {
useEffect(() => {
console.log(`Setting up subscription for user ${userId}`);
// The logic to subscribe to a user's status would go here.
// e.g., subscribeToUserStatus(userId);
return () => {
// This runs before the next effect OR on unmount.
console.log(`Tearing down subscription for user ${userId}`);
// e.g., unsubscribeFromUserStatus(userId);
};
}, [userId]); // The effect depends on userId
return <div>Showing profile for User ID: {userId}</div>;
}
export default function App() {
const [currentUserId, setCurrentUserId] = useState(1);
return (
<div>
<button onClick={() => setCurrentUserId(1)}>User 1</button>
<button onClick={() => setCurrentUserId(2)}>User 2</button>
<UserProfile userId={currentUserId} />
</div>
);
}
Walkthrough:
- Initial Render:
ApprendersUserProfilewithuserId={1}.- Console:
Setting up subscription for user 1
- Console:
- Click "User 2":
Appre-rendersUserProfilewithuserId={2}.- The
userIddependency has changed from1to2. - React runs the cleanup from the previous render (where
userIdwas1). - Console:
Tearing down subscription for user 1 - React runs the new effect with the current props (
userIdis2). - Console:
Setting up subscription for user 2
- The
Test your understanding!
You are building a component that listens for resize events on the window object. On each resize, it should log the new window width.
function WindowWidthLogger() {
const [width, setWidth] = useState(window.innerWidth);
// How would you use useEffect to...
// 1. Add the event listener when the component mounts?
// 2. Update the `width` state when the window is resized?
// 3. Remove the event listener when the component unmounts to prevent a memory leak?
return <div>Current window width: {width}px</div>;
}
Write the useEffect hook that accomplishes all three goals.
Show answer
The correct approach is to use a single useEffect with an empty dependency array. The effect sets up the listener, and its cleanup function removes it.
function WindowWidthLogger() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
// This is the event handler function.
const handleResize = () => {
console.log('Window resized!');
setWidth(window.innerWidth);
};
// 1. Add the event listener on mount.
window.addEventListener('resize', handleResize);
console.log('Event listener added.');
// 3. Return a cleanup function to remove the listener on unmount.
return () => {
window.removeEventListener('resize', handleResize);
console.log('Event listener removed.');
};
}, []); // [] means this effect runs once on mount and cleans up on unmount.
return <div>Current window width: {width}px</div>;
}
This single effect correctly manages the entire lifecycle of the event listener, attaching it on mount and detaching it on unmount.
Summary: The useEffect Lifecycle Patterns
This flowchart provides a great visual summary of how different hooks, including useEffect, fit into the component lifecycle. Notice how useEffect runs after the render and commit phases and has a distinct cleanup phase.
Here is the cheat sheet for mapping useEffect to lifecycle events:
- Run on Mount (componentDidMount):
useEffect(() => { /* ... */ }, []); - Run on Unmount (componentWillUnmount):
useEffect(() => { return () => { /* cleanup ... */ }; }, []); - Run on Update (componentDidUpdate):
useEffect(() => { /* ... */ }, [dep1, dep2]);
It's important to remember that an effect with dependencies (the "update" pattern) will also run its cleanup function on final unmount. The cleanup is not just for updates; it runs whenever the effect is about to be replaced or removed.
Conclusion
You now have a solid framework for understanding how useEffect can be used to manage logic that needs to run at specific points in a component's life. You can reliably perform actions on mount, clean up resources on unmount, and react to changes during updates.
Key Takeaways:
- Mounting:
useEffectwith an empty[]dependency array runs once after the initial render. - Unmounting: The
cleanupfunction returned from an effect runs when the component is removed. For an effect with an empty[]array, this happens only on unmount. - Updating:
useEffectwith dependencies[dep]re-runs when a dependency changes. The process is always:cleanupfrom the previous effect, then run the new effect.
In our next lesson, we will focus exclusively on the cleanup function. You've seen it used for unmounting and updates, but we'll dive deeper into crucial use cases like aborting stale network requests to prevent race conditions—a common and subtle bug in data-fetching components.