---
title: "Why does useEffect run twice in development?"
description: "In development, React Strict Mode mounts components twice to expose effects without cleanup. Learn why it happens, why production is unaffected, and how to write effects that cope."
url: https://www.danny.engineering/answer/react/why-does-useeffect-run-twice-in-development
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T17:25:00.000Z
tags: ["React"]
---

# Why does useEffect run twice in development?

## The short answer


React Strict Mode deliberately mounts each component, unmounts it, and mounts it again in development. Your effect runs, its cleanup runs, then the effect runs again. This only happens in development. The fix is not to stop it, but to give the effect a cleanup function so running it twice does no harm.


```typescript
useEffect(() => {
  const connection = createConnection(roomId);
  connection.connect();

  return () => {
    connection.disconnect(); // undo whatever the effect did
  };
}, [roomId]);
```


## Why it happens


Effects are meant to sync your component with something outside React: a subscription, a timer, a socket, a third-party widget. In a real app, components mount and unmount many times. Users navigate away and back, React may hide and restore parts of the tree with features like `Activity`, and fast refresh remounts components while you edit.


If an effect sets something up but never tears it down, those remounts leave duplicates behind: two event listeners, two intervals, two open sockets. Strict Mode surfaces this early by running one extra setup and cleanup cycle straight after the first mount. If your component behaves the same after that cycle, your effect is safe.


Strict Mode is switched on with the `StrictMode` component. Next.js enables it by default for the App Router, and most new project templates wrap the app in it too. React 19 still does the double mount in development, and production builds never do.


## How to fix it


### Add a cleanup that mirrors the setup


Every `add` needs a `remove`, every `subscribe` an `unsubscribe`, every `setInterval` a `clearInterval`.


```typescript
useEffect(() => {
  function handleResize() {
    setWidth(window.innerWidth);
  }
  window.addEventListener('resize', handleResize);
  return () => window.removeEventListener('resize', handleResize);
}, []);
```


### Ignore stale results when fetching


Fetching in an effect will send two requests in development. That is fine as long as the first result cannot overwrite the second. Use an `ignore` flag or an `AbortController`.


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

  fetch(`/api/users/${userId}`, { signal: controller.signal })
    .then((res) => res.json())
    .then(setUser)
    .catch((error) => {
      if (error.name !== 'AbortError') throw error;
    });

  return () => controller.abort();
}, [userId]);
```


In a framework such as Next.js, prefer fetching on the server or with a data library that caches and de-duplicates requests, so you do not need an effect at all.


### Move one-off actions out of effects


Some code should only ever run once per user action, such as sending a purchase or logging an analytics event for a click. Put that code in the event handler that triggers it, not in an effect.


```typescript
function BuyButton({ productId }: { productId: string }) {
  async function handleClick() {
    await fetch('/api/buy', { method: 'POST', body: JSON.stringify({ productId }) });
  }
  return <button onClick={handleClick}>Buy</button>;
}
```


For code that should run once when the app starts, such as initialising an SDK, run it at module level outside any component, or guard it with a module-level variable.


## Common pitfalls

- Removing `StrictMode` to make the double run go away. The bug it found is still there and will appear in production when components remount.
- Using a ref flag such as `hasRun.current` to skip the second run. It hides the problem and breaks when React genuinely remounts the component.
- Assuming production also runs effects twice. It does not; if you see duplicates there, look for a missing cleanup or a component that mounts twice.
- Forgetting that the render function also runs twice in Strict Mode. Keep rendering pure and free of side effects.

## Related reading

- [React: StrictMode](https://react.dev/reference/react/StrictMode)
- [React: Synchronising with effects](https://react.dev/learn/synchronizing-with-effects)
