React components go through a lifecycle every time they appear on the screen:
Mount → component is added to the DOM
Update → state or props change
Unmount → component is removed
In class components, you had lifecycle methods like:
componentDidMount
componentDidUpdate
componentWillUnmount
In function components, all of this is handled through useEffect.
useEffect lets you perform side effects in your components. Side effects are operations that interact with the outside world, such as data fetching, subscriptions, manually changing the DOM, or setting up timers.
It runs after React has finished rendering (and after the browser has painted), making it the perfect place for operations that interact with the outside world.
It’s perfect for:
Fetching API data
Updating the document title
Subscribing to events
Running timers
Cleaning up when a component unmounts
useEffect(() => {
// Side effect logic here
return () => {
// Cleanup logic (optional)
};
}, [dependencies]); // Dependency array
By default, the effect runs after every render (initial render + updates).
You can control when it runs using the dependency array ([]).
useEffect(() => {...}, []) → runs only once on mount
useEffect(() => {...}, [dependencies]) → runs on mount + when `dependencies` changes
useEffect(() => {...}) → runs after every render
You can return a cleanup function to prevent memory leaks (e.g., unsubscribing, clearing timers).
import { useEffect, useState } from "react";
function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(data => setUsers(data));
}, []); // empty dependency array → run once after first render
return <div>{users.length} users loaded</div>;
}
import { useEffect, useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]); // runs whenever count changes
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}