DG
DevGuide
Run Code
Home/React/useEffect
⚛ React3 / 4

useEffect

📌 WHAT

useEffect lets you run side effects after rendering — things like fetching data, setting up subscriptions, updating the document title, or integrating with non-React libraries.

💡 WHY

React components should be pure functions (no side effects during render). useEffect is React's dedicated place for code that needs to interact with the outside world.

⏰ WHEN / WHERE

Fetching data on component mount, listening to events, syncing with localStorage, setting up timers, updating page title. The dependency array controls WHEN it runs.

🔧 HOW

useEffect(callback, [dependencies]). Empty [] = run once on mount. [id] = run when id changes. No array = run after every render (usually wrong).

Code Examples

#1useEffect patterns

useEffect patterns
tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"use client";
import { useState, useEffect } from "react";
// Pattern 1: Fetch data on mount
function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
// [] = run once when component appears (mounts)
useEffect(() => {
async function fetchUsers() {
try {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
const data = await res.json();
setUsers(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchUsers();
}, []); // empty array = run once
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}
// Pattern 2: Re-fetch when a dependency changes
function UserProfile({ userId }: { userId: number }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
.then(r => r.json())
.then(setUser);
}, [userId]); // re-runs whenever userId changes
return <div>{user?.name}</div>;
}
// Pattern 3: Cleanup (event listeners, subscriptions)
function WindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", handleResize);
// Cleanup function — runs when component unmounts
return () => {
window.removeEventListener("resize", handleResize);
};
}, []); // only set up once
return <p>Window width: {width}px</p>;
}

Practice This Concept

Open the playground, paste any example, and experiment. The best way to learn is by breaking things.

Open in Playground