← React Beginner Questions - Set 2 Q14

What is the useEffect hook used for?

React Beginner Questions - Set 2

For everything that must happen outside rendering: fetching, subscriptions, timers. The cleanup function is the half people forget.

Example

import { useEffect, useState } from 'react';

export default function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const controller = new AbortController();

    fetch(`/api/users/${userId}`, { signal: controller.signal })
      .then(r => (r.ok ? r.json() : Promise.reject(r.status)))
      .then(setUser)
      .catch(err => {
        if (err.name !== 'AbortError') setError(String(err));
      });

    return () => controller.abort();   // runs before the next effect
  }, [userId]);                        // re-run only when userId changes

  if (error) return <p>Error: {error}</p>;
  if (!user) return <p>Loading…</p>;
  return <h2>{user.name}</h2>;
}

What to notice

← Back to the question list