Side Effect

useEffect

useEffect(callback, [deps])

synchronization, data fetching, subscriptions. The bridge between React and the outside world.

Side Effects

React components are pure by default. But sometimes you need to reach outside—fetch data, subscribe to events, or manipulate the DOM. That's a 'side effect'.

The Mount

By default, useEffect runs after *every* render. But with an empty dependency array `[]`, it runs only once: when the component first appears (mounts).

Dependencies

You can tell React exactly when to re-run the effect. If you pass variables (dependencies) in the array, the effect runs whenever those values change.

Cleanup Phase

Effects can return a cleanup function. React runs this before the component unmounts (or before re-running the effect) to prevent memory leaks.

Interactive Flow

Let's see it in action! Click the button to trigger a state update. Watch how React re-renders the component, checks the dependency array, and then executes the effect.

Basic Usage

Always place side effects inside useEffect. Never run them directly in the component body.

DataFetcher.tsx
import { useEffect, useState } from 'react';
                            
function UserProfile({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    // This runs after current render
    fetch(`/api/user/${userId}`)
      .then(res => res.json())
      .then(data => setUser(data));
  }, [userId]); // Only re-run if 'userId' changes

  if (!user) return <div>Loading...</div>;
  return <div><h1>{user.name}</h1></div>;
}
Fetching data on mount or update

Cleaning Up

If your effect creates a subscription or timer, you MUST clean it up to avoid memory leaks. Return a function to do this.

Timer.tsx
useEffect(() => {
  const timerId = setInterval(() => {
    console.log('Tick!');
  }, 1000);

  // Cleanup function
  return () => {
    clearInterval(timerId); // Stop the timer!
    console.log('Cleaned up');
  };
}, []); // Empty array = run once on mount
Interval with Cleanup
AlgoAnimator: Interactive Data Structures