ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

React.js Tutorial• 6 min read

Side Effects with useEffect

Data fetching, event listeners, timers, and the dependency array

The useEffect Hook allows you to perform side effects in your components. Some examples of side effects are: fetching data, directly updating the DOM, and timers.

The Dependency Array

No dependency array: useEffect(() => {}) runs on EVERY render.

Empty dependency array []: runs ONCE when the component mounts.

With dependencies [prop, state]: runs when any specified dependency changes.

Cleanup function: return a function return () => cleanup() to unsubscribe or clear timers.

Fetching Data Inside useEffect
import { useState, useEffect } from 'react';

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let isMounted = true;
    setLoading(true);

    fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
      .then(res => res.json())
      .then(data => {
        if (isMounted) {
          setUser(data);
          setLoading(false);
        }
      });

    return () => { isMounted = false; };
  }, [userId]); // Only re-run when userId prop changes

  if (loading) return <p>Loading user profile...</p>;
  return <div><h3>{user.name}</h3><p>{user.email}</p></div>;
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

How do you tell useEffect to only run ONCE when the component first mounts?