Why Fetch Happens in useEffect
What you'll learn: Why network requests must be placed inside useEffect instead of directly in your component body.
The Fundamental Problem
When you fetch data, you're performing a side effect — an operation that reaches outside your component to interact with the external world (in this case, a server). React's render phase must be pure and synchronous, meaning it can't contain operations that:
- Take unpredictable amounts of time
- Modify external state
- Trigger asynchronous callbacks
If you tried to fetch data directly during render, chaos would ensue.
What Would Go Wrong
Imagine placing fetch() directly in your component body:
function UserProfile() {
// ❌ WRONG: Fetch during render
fetch('/api/user').then(data => {
// When does this run? After render finishes!
// How do you update state here? It triggers another render!
});
return <div>Loading...</div>;
}
This creates an infinite loop: fetch triggers → render completes → fetch triggers → render completes... React would crash or freeze.
Why useEffect is the Solution
useEffect runs after the render and commit phases are complete. By that time:
- Your component has safely rendered to the screen
- The DOM has been updated
- React is ready to handle side effects
- You can safely update state based on the response
function UserProfile() {
const [user, setUser] = useState(null);
useEffect(() => {
// ✅ CORRECT: Fetch after render
fetch('/api/user')
.then(res => res.json())
.then(data => setUser(data));
}, []);
return user ? <div>{user.name}</div> : <div>Loading...</div>;
}
Key Takeaway: Network requests happen in useEffect because they must run after render completes, not during the render itself, preventing infinite loops and keeping your render function pure.