Mastering useEffect Hook in React
Learn how to perform side effects in React functional components using useEffect.

What is useEffect?#
useEffect is a hook that lets you perform side effects in functional components. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount combined in class components.
Basic Syntax#
Code
import { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
});
return <div>Count: {count}</div>;
}Effect with Dependencies#
Code
// Runs only on mount
useEffect(() => {
console.log("Component mounted");
}, []);
// Runs when count changes
useEffect(() => {
console.log("Count changed:", count);
}, [count]);
// Runs when any dependency changes
useEffect(() => {
fetchData(userId);
}, [userId]);Cleanup Function#
Code
useEffect(() => {
const timer = setInterval(() => {
setCount(c => c + 1);
}, 1000);
// Cleanup function
return () => {
clearInterval(timer);
};
}, []);Data Fetching Example#
Code
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchUser() {
try {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
setUser(data);
} catch (error) {
console.error("Error:", error);
} finally {
setLoading(false);
}
}
fetchUser();
}, [userId]);
if (loading) return <div>Loading...</div>;
return <div>{user?.name}</div>;
}Common Use Cases#
- Data fetching from APIs
- Setting up subscriptions
- Manually changing the DOM
- Setting up timers
- Adding event listeners
Best Practices#
- Always include dependencies in the dependency array
- Clean up subscriptions and timers
- Don't forget the empty dependency array for mount-only effects
- Use multiple useEffect hooks to separate concerns