🔥 0
0
Lesson 9 of 10 20 min +100 XP

useEffect: Side Effects

Side effects are anything that affects something outside your component: API calls, timers, subscriptions, DOM manipulation.

Basic useEffect

useEffect(() => {
  // This runs after every render
  console.log('Component rendered!');
});

Dependency Array

Control when the effect runs:

// Runs after EVERY render
useEffect(() => { });

// Runs ONCE on mount
useEffect(() => { }, []);

// Runs when count changes
useEffect(() => { }, [count]);

// Runs when count OR name changes
useEffect(() => { }, [count, name]);

Cleanup Function

Return a function to clean up:

useEffect(() => {
  const timer = setInterval(() => {
    console.log('Tick');
  }, 1000);

  // Cleanup: runs before next effect or unmount
  return () => clearInterval(timer);
}, []);

Common Use Cases

Use CaseExample
Fetch dataAPI calls on mount
SubscriptionsWebSocket connections
Event listenersWindow resize, scroll
Document titleUpdate based on state
TimersIntervals, timeouts

The Mental Model

Think of useEffect as:

  • "After render, do this"
  • "Before the next effect (or unmount), clean up"

Explore useEffect below!

Rendering Lists