React Lifecycle & Effects
Learn component lifecycle stages and how useEffect runs side effects in React.
Component Lifecycle and Effects (useEffect)
Every React component goes through different stages during its lifetime. A component is first created, then displayed on the screen, updated when its data changes, and finally removed when it is no longer needed. These stages are known as the component lifecycle.
In modern React, the useEffect Hook is used to perform actions during these lifecycle stages. It allows your application to run code after a component has been rendered, making it useful for tasks like loading data, updating the page title, setting timers, or listening for browser events.
Understanding the component lifecycle and the useEffect Hook is essential for building dynamic and efficient React applications.
What is the Component Lifecycle?
The component lifecycle describes the different stages a React component goes through from the moment it is created until it is removed.
The lifecycle has three main stages:
- Mounting
- Updating
- Unmounting
Mounting
Mounting is the first stage of a component's lifecycle. It happens when the component is created and displayed on the screen for the first time.
Common tasks during mounting include:
- Loading data from an API
- Displaying initial content
- Starting a timer
- Setting the page title
This is one of the most common uses of the useEffect Hook.
Updating
A component enters the updating stage whenever its state or props change.
For example:
- A user clicks a button.
- A form value changes.
- New data is received from a server.
React automatically re-renders the component to display the latest information.
Sometimes you may want to perform additional tasks whenever this update happens, such as saving data or displaying a notification. The useEffect Hook can handle these situations.
Unmounting
Unmounting happens when a component is removed from the screen.
Examples include:
- Closing a popup window
- Leaving a page
- Removing a component from the interface
Before the component disappears, React gives you an opportunity to clean up resources. This process is called cleanup.
What is useEffect?
The useEffect Hook lets you perform side effects after a component renders.
A side effect is any task that happens outside of simply displaying the user interface.
Examples include:
- Fetching data from an API
- Updating the browser title
- Starting or stopping timers
- Adding event listeners
- Cleaning up resources
Basic useEffect Example
import { useEffect } from "react";
function App() {
useEffect(() => {
console.log("Component Loaded");
}, []);
return <h1>Welcome to React</h1>;
}Explanation
- useEffect() runs after the component is displayed.
- The empty dependency array [] means the effect runs only once when the component mounts.
Running useEffect When Data Changes
Sometimes you want an effect to run only when a specific value changes.
import { useState, useEffect } from "react";
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Count changed:", count);
}, [count]);
return (
<button onClick={() => setCount(count + 1)}>
{count}
</button>
);
}How It Works
- The component renders with an initial value of 0.
- When the button is clicked, the state changes.
- Because count is listed in the dependency array, useEffect runs again.
This is useful when you want to react to changes in specific data.
Cleaning Up Effects
Some effects need to be cleaned up when a component is removed. For example, timers should be stopped to prevent unnecessary background work.
import { useEffect } from "react";
function Timer() {
useEffect(() => {
const timer = setInterval(() => {
console.log("Running...");
}, 1000);
return () => {
clearInterval(timer);
};
}, []);
return <h2>Timer Started</h2>;
}Explanation
- The timer starts when the component mounts.
- The cleanup function stops the timer when the component unmounts.
- This helps avoid memory leaks and improves performance.
Common Uses of useEffect
Developers commonly use useEffect for:
- Fetching data from APIs
- Updating the page title
- Starting timers
- Watching browser events
- Saving data to local storage
- Cleaning up timers or event listeners
These tasks are performed after React updates the user interface.
Best Practices
When using useEffect:
- Keep effects focused on one task.
- Use the dependency array correctly.
- Clean up timers and event listeners when needed.
- Avoid unnecessary effects that run on every render.
- Write simple and readable effect functions.
These practices help improve performance and maintainability.