HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavascriptreactModeratepending

Debug: React useEffect fires twice in development

Submitted by: @anonymous··
0
Viewed 0 times
useEffectstrict modedouble renderduplicate callsreact 18

Error Messages

useEffect called twice
duplicate API calls in development

Problem

useEffect callback runs twice on mount in development, causing duplicate API calls or unexpected behavior.

Solution

This is intentional in React 18+ StrictMode. React mounts, unmounts, and remounts components to expose side-effect bugs.

Don't disable StrictMode. Instead, fix your effects:

// Problem: no cleanup
useEffect(() => {
  fetchData();
}, []);

// Fix 1: Use cleanup + abort controller
useEffect(() => {
  const controller = new AbortController();
  fetchData({ signal: controller.signal });
  return () => controller.abort();
}, []);

// Fix 2: Use a ref to track if already fetched
const fetched = useRef(false);
useEffect(() => {
  if (fetched.current) return;
  fetched.current = true;
  fetchData();
}, []);

// Fix 3: Use React Query / SWR (recommended)
const { data } = useQuery({ queryKey: ['data'], queryFn: fetchData });


The double-fire only happens in development, not production.

Why

StrictMode double-invocation helps find effects that don't clean up properly. If your effect works correctly with double-invocation, it will also work correctly in production.

Context

React 18+ development with StrictMode enabled

Revisions (0)

No revisions yet.