All questions

How do I run useEffect only once in React and clean up correctly?

My effect fetches data on mount, and in development it seems to run twice.

Answer

Pass an empty dependency array so the effect runs after the first render only, and return a cleanup function that cancels work still in flight. In React 18 development builds, `StrictMode` mounts, unmounts and remounts each component once to expose missing cleanup. The second run is expected and does not happen in production. With an `AbortController` in cleanup, the first request is cancelled and only the second one completes.

JavaScript solution

import { useEffect, useState } from 'react';

export function Users() {
  const [users, setUsers] = useState([]);
  const [error, setError] = useState(null);

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

    fetch('/api/users', { signal: controller.signal })
      .then((res) => res.json())
      .then(setUsers)
      .catch((err) => {
        if (err.name !== 'AbortError') setError(err);
      });

    return () => controller.abort(); // cleanup
  }, []); // empty array: run once after mount

  if (error) return <p>Could not load users.</p>;
  return <ul>{users.map((u) => <li key={u.id}>{u.name}</li>)}</ul>;
}

Edited by Jack · joysait@rediffmail.com

Add a Q&A

Drop an image here or click to choose. It is saved as images/N.ext.

Live preview

Publish to GitHub

Drafts 0

Drafts live in this browser only. Download or push them to make them public.

    Files to commit

    data/qa.json
    sitemap.xml
    robots.txt

    Push with the GitHub API

    Uses a fine-grained token with Contents: Read and write on your repo. The token stays in this page's memory only: it is never saved or sent anywhere except api.github.com.