StackDevLife
๐Ÿ›Bug of the DayIntermediateReact, Frontend, Hooks

Why useEffect Runs Twice in React (Not a Bug)

~1 min read
๐Ÿ›TL;DR

If your useEffect runs twice in development, it is due to React Strict Mode and not an actual bug.

The Bug

useEffect runs twice on component mount, causing duplicate API calls or logs.

Root Cause

React Strict Mode intentionally invokes effects twice in development to detect side effects.

The Fix

If you notice that your useEffect hook runs twice when a component mounts, it can be confusing and may look like a bug.

This behavior happens in development mode when React Strict Mode is enabled. React intentionally runs certain lifecycle methods twice to help detect side effects and ensure your code is safe.

Example:

JavaScript
useEffect(() => {
console.log("Effect running");
}, []);

In development, this may log twice. In production, it will run only once.

You do not need to fix this. Instead, make sure your side effects are safe to run multiple times.

Avoid disabling Strict Mode unless absolutely necessary, as it helps catch potential issues early.

ReactuseEffectDebuggingFrontend
๐Ÿ›

Get a new Bug of the Day in your inbox

Subscribe to Stack Dev Life โ€” free, no spam, unsubscribe anytime.

Subscribe free โ†’