Module 5.1: Component Lifecycle & useEffect

🎯 What You’ll Learn
After this module, you’ll master:
- Component Lifecycle: Understand the three core stages: Mount, Update, and Unmount.
useEffectHook: Your primary tool for managing side effects within Function Components.- Dependency Array: How to control when
useEffectruns to prevent infinite loops. - Cleanup Function: How to prevent memory leaks when a component is destroyed.
1. The Component Lifecycle
Just like humans, every component in React goes through three main stages. Understanding these three stages (and their internal phases) is key to gaining control over your application.

1.1. The Three Stages
- Mounting (Birth):
- This happens when the component is first added to the DOM.
- Process: Initialize
state-> RenderUI-> Update DOM -> Run Side Effects (useEffect).
- Updating (Change):
- Occurs when
propschange,statechanges, or the parent component re-renders. - Process: Re-render
UI-> Compare diff -> Update DOM -> Re-run Side Effects.
- Occurs when
- Unmounting (Death):
- When the component is removed from the DOM.
- Process: Perform cleanup for Side Effects to prevent memory leaks.
1.2. The Two Processing Phases
React divides its processing into two distinct phases:
-
Render Phase (Calculation):
- React runs your
functioncomponent. - This phase must be “Pure” (no side effects, no API calls, no direct DOM mutations).
- It only calculates what the
UIshould look like.
- React runs your
-
Commit Phase (Execution):
- React actually modifies the DOM (adds nodes, updates text).
- Once the DOM updates are complete, React then runs Side Effects (
useEffect). - This is the safe place to make API calls, interact with the DOM, or set
setTimeout.
For more details, see the Lifecycle Diagram
2. Basic useEffect Hook

In Function Components, we use useEffect to handle Side Effects (ancillary tasks) at different points in the component’s lifecycle.
2.1. Syntax
useEffect(() => {
// Code to run here (Effect)
return () => {
// Cleanup code (Optional)
};
}, [dependencies]); // Dependency array2.2. Common Use Cases
| Stage | Dependency Array [] | Description |
|---|---|---|
| Mount Only | [] (Empty) | Runs only once after the initial render. Commonly used for API calls, event setup. |
| Update | [prop, state] | Runs once initially AND whenever a variable in the array changes. |
| Every Render | (Omitted) | Runs after every render. ⚠️ Use sparingly, as it can cause performance issues. |
| Unmount | return () => {} | The cleanup function runs before the component disappears. |
3. Diving Deeper into Each Stage
3.1. Mounting (Run Once)
Use an empty dependency array [].
import { useEffect } from 'react';
function Welcome() {
useEffect(() => {
console.log('✅ Component has appeared (Mounted)');
// Example: Fetch user information via API
// fetchUser();
}, []); // <--- Important: Empty array
return <h1>Hello World</h1>;
}3.2. Updating (Tracking Variables)
Runs when the count variable changes.
function Counter() {
const [count, setCount] = useState<number>(0);
useEffect(() => {
console.log(`🔄 Count has changed to: ${count}`);
document.title = `Count: ${count}`; // Update the web page title
}, [count]); // <--- Re-runs when 'count' changes
return <button onClick={() => setCount(count + 1)}>+</button>;
}3.3. Unmounting (Cleanup)
Use the return function inside useEffect. This is a critically important step to prevent Memory Leaks.
Example: If you setInterval (set a timer) but don’t clear it when the component unmounts, the timer will continue running in the background indefinitely.
function Timer() {
useEffect(() => {
const timerId = setInterval(() => {
console.log('⏰ Tick tack...');
}, 1000);
// CLEANUP FUNCTION
return () => {
console.log('🗑️ Cleaning up timer');
clearInterval(timerId); // Clear the interval
};
}, []);
return <div>Timer is running...</div>;
}4. Hands-on Labs
Lab 1: Lifecycle Console Dashboard
Instead of hidden console.log messages in Developer Tools, let’s build a “Visual Logger” directly into the interface.
- A toggle button to Mount/Unmount the child
component. - An
areato display event logs: “Born”, “Updated”, “Died” with different colors.

💡 Hint:
- Use
useEffectwith[]tologwhen thecomponentMounts.- Use the
returnfunctionofuseEffecttologwhen thecomponentUnmounts.- Use
propscallbacks to send logs from the child to the parent and store them in thelogsstate(array).
Lab 2: Retro Digital Timer (Neon Style)
Create a countdown timer with a Cyberpunk/Retro style.
- Display hours : minutes : seconds.
- Neon Glow effect.
- Ensure no Memory Leaks when hiding the clock.

💡 Hint:
- Use
setIntervalinsideuseEffectto update the time every second.- IMPORTANT: You must call
clearIntervalin thecleanupfunction. Otherwise, when the clock is hidden, the timer will still run in the background, causing errors or consuming resources.- Use
new Date().toLocaleTimeString()to get the current time string.
5. Summary
- Mount (
[]): Use for datasetup, API calls, and event listener registration. - Update (
[deps]): Use to react tostate/propschanges (e.g., Autosave, Sync). - Unmount (
cleanup): Use toclearInterval,removeEventListener, and cancel requests. - Always remember: If you create anything that runs in the background (Intervals, Listeners), you MUST clean it up in the
cleanupfunction.