📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials React Modern Development useEffect

useEffect

6 min read Quiz at the end
useEffect runs code after a render. Pass [] to run once on mount, [id] to run when id changes, or nothing for every render. Return a cleanup function to clear timers and subscriptions to prevent memory leaks.

useEffect Hook

import { useState, useEffect } from "react";

function UserCard({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetch(`/api/users/${userId}`)
      .then(r => r.json())
      .then(setUser);

    // Cleanup
    return () => console.log("cleanup");
  }, [userId]); // runs when userId changes

  if (!user) return 

Loading...

; return

{user.name}

; }
Topic Quiz · 5 questions

Test your understanding before moving on

1. What is useEffect used for?
💡 useEffect handles side effects that happen outside the render cycle.
2. When does useEffect run by default?
💡 Without a dependency array, useEffect runs after every render.
3. Empty dependency array [] means:
💡 An empty [] dependency array means the effect runs only once after the first render.
4. What is the cleanup function?
💡 The function returned from useEffect is called for cleanup on unmount or before re-running.
5. Where should you NOT use useEffect?
💡 Never update state synchronously during render — it causes infinite loops.