Course contentsShow
← React
Lesson 568 of 2,39616. useEffect for Data FetchingFree lesson

Why Fetch Happens in useEffect

Understand why side effects like network requests must run after render, not during the render phase itself.

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:

  1. Your component has safely rendered to the screen
  2. The DOM has been updated
  3. React is ready to handle side effects
  4. 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.