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