ReactNext.jsError Fix2026 Updated

useEffect Running Twice React 18— Fixed [2026]

Also covers: API called twice · StrictMode double render · fetch running twice in Next.js

January 20266 min readReact 18 · Next.js 13–15

⚡ The Real Fix — Add a Cleanup Function

components/DataFetcher.jsx
useEffect(() => {
  const controller = new AbortController()

  fetch('/api/data', { signal: controller.signal })
    .then(res => res.json())
    .then(data => setData(data))
    .catch(err => {
      if (err.name === 'AbortError') return  // ignore — this is expected
      console.error(err)
    })

  return () => controller.abort()  // ← cleanup cancels the first call
}, [])

Why Does useEffect Run Twice in React 18?

Console Output
// You see this in console in development:
Fetching data...   // ← first mount
Fetching data...   // ← second mount (StrictMode!)

// Your API gets called twice, state gets set twice,
// event listeners get attached twice...

React 18 intentionally runs useEffect twice in development when <React.StrictMode> is enabled (which Next.js enables by default). The sequence is: mount → run effects → unmount → cleanup → remount → run effects again.

This is not a bug — it is React stress-testing your components to ensure effects are cleanup-safe. If your effect causes problems when run twice, it means the cleanup function is missing or incomplete.

Effect typeCorrect cleanup
fetch / API callAbortController → abort() in cleanup
EventListenerremoveEventListener in cleanup
WebSocket / SSEclose() the connection in cleanup
setInterval / setTimeoutclearInterval / clearTimeout in cleanup
Database write / side effectRef flag to prevent second execution
1

Add a Cleanup Function — The Correct Approach

Every useEffect that does async work needs this
3 min

Every useEffect that starts an asynchronous operation should return a cleanup function that cancels or ignores the result when the component unmounts.

The cleanup pattern for every effect type
// ✅ Fetch with AbortController
useEffect(() => {
  const controller = new AbortController()
  fetch('/api/user', { signal: controller.signal })
    .then(r => r.json()).then(setUser)
    .catch(e => { if (e.name !== 'AbortError') console.error(e) })
  return () => controller.abort()
}, [userId])

// ✅ Event listener
useEffect(() => {
  window.addEventListener('resize', handleResize)
  return () => window.removeEventListener('resize', handleResize)
}, [])

// ✅ setInterval
useEffect(() => {
  const id = setInterval(tick, 1000)
  return () => clearInterval(id)
}, [])

// ✅ WebSocket
useEffect(() => {
  const ws = new WebSocket('wss://api.example.com')
  ws.onmessage = (e) => setMessages(m => [...m, e.data])
  return () => ws.close()
}, [])
2

Deduplicate API Calls With AbortController

API called twice — most painful symptom
3 min

When StrictMode mounts twice, an unguarded fetch fires twice. The AbortController pattern cancels the first call when the component unmounts, so only the second (real) call completes.

hooks/useData.js
import { useState, useEffect } from 'react'

export function useData(url) {
  const [data, setData]   = useState(null)
  const [error, setError] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const controller = new AbortController()
    setLoading(true)

    async function load() {
      try {
        const res = await fetch(url, { signal: controller.signal })
        if (!res.ok) throw new Error('Request failed: ' + res.status)
        const json = await res.json()
        setData(json)
      } catch (err) {
        if (err.name === 'AbortError') return  // expected — ignore
        setError(err.message)
      } finally {
        setLoading(false)
      }
    }

    load()
    return () => controller.abort()
  }, [url])

  return { data, error, loading }
}
3

Prevent Duplicate Side Effects With a Ref

Database writes, analytics, one-time operations
2 min

For side effects that must only run once — analytics events, database writes, initialisation — use a ref to track whether it has already run.

components/Analytics.jsx
import { useEffect, useRef } from 'react'

export default function ProductPage({ productId }) {
  const tracked = useRef(false)

  useEffect(() => {
    if (tracked.current) return   // already ran — skip second invocation
    tracked.current = true

    // This now only fires once even in StrictMode
    analytics.track('product_viewed', { productId })
  }, [productId])

  return <div>Product {productId}</div>
}

The ref approach is for truly one-time operations. For data fetching, prefer AbortController (Fix 2) because it handles network cancellation properly.

4

Remove StrictMode — Use Only as Last Resort

Not recommended — hides the real problem
1 min

You can remove StrictMode to stop the double invocation but this hides the underlying cleanup bug rather than fixing it. Only consider this temporarily while debugging.

app/layout.jsx
// ❌ Not recommended — disables StrictMode entirely
export default function RootLayout({ children }) {
  return (
    <html>
      <body>{children}</body>  {/* removed React.StrictMode */}
    </html>
  )
}

// Next.js reactStrictMode toggle (next.config.js)
module.exports = {
  reactStrictMode: false,  // ← removes StrictMode — not recommended
}

Removing StrictMode means React will not warn you about other cleanup bugs, deprecated APIs, or unexpected side effects. Fix the cleanup instead.

5

Use a Data Fetching Library

Best long-term solution — handles deduplication automatically
5 min

Libraries like SWR and TanStack Query handle deduplication, caching, and race conditions automatically. They are immune to the StrictMode double-invoke problem.

terminal
npm install swr
# or
npm install @tanstack/react-query
SWR — recommended for Next.js
import useSWR from 'swr'

const fetcher = (url) => fetch(url).then(r => r.json())

export default function UserProfile({ userId }) {
  const { data, error, isLoading } = useSWR(`/api/users/${userId}`, fetcher)

  if (isLoading) return <div>Loading...</div>
  if (error)     return <div>Error: {error.message}</div>
  return <div>{data.name}</div>
  // No useEffect needed — SWR handles everything
}
TanStack Query
import { useQuery } from '@tanstack/react-query'

export default function UserProfile({ userId }) {
  const { data, isLoading } = useQuery({
    queryKey: ['user', userId],
    queryFn: () => fetch(`/api/users/${userId}`).then(r => r.json()),
  })

  if (isLoading) return <div>Loading...</div>
  return <div>{data.name}</div>
}
6

Analytics and Tracking — Fire Once Only

Page view events firing twice
2 min
hooks/usePageView.js
import { useEffect, useRef } from 'react'
import { usePathname } from 'next/navigation'

export function usePageView() {
  const pathname = usePathname()
  const lastPath = useRef(null)

  useEffect(() => {
    // Only track when path actually changes, not StrictMode remount
    if (pathname === lastPath.current) return
    lastPath.current = pathname
    analytics.page({ path: pathname })
  }, [pathname])
}

This Only Happens in Development

It is worth repeating: the double invocation is a development-only behaviour. React StrictMode does not run in production. Your users will never see the doubled effects. The purpose is to make you write correct cleanup code, which protects against real production bugs when components unmount and remount during navigation.

Prevention — Write Cleanup-Safe Effects

Frequently Asked Questions

Why does useEffect run twice in React 18?+
React 18 StrictMode intentionally mounts, unmounts, and remounts every component in development to help you find cleanup bugs. useEffect runs twice (mount → unmount → mount) so you notice if your effects do not properly clean up. This does NOT happen in production.
Does useEffect run twice in production?+
No. The double invocation only happens in development when React StrictMode is enabled. In production, useEffect runs exactly once per mount (or once per dependency change).
How do I make useEffect run only once in React 18?+
The correct approach is to add a cleanup function. For API calls: use AbortController and abort in the cleanup. For subscriptions: unsubscribe in cleanup. For event listeners: removeEventListener in cleanup. This makes the double run safe.
How do I stop useEffect from fetching data twice?+
Use AbortController: const controller = new AbortController(); fetch(url, { signal: controller.signal }). In cleanup: return () => controller.abort(). The second call aborts the first, so only one fetch completes.
useEffect running twice is causing duplicate database writes — how to fix?+
Use a ref flag: const didRun = useRef(false); if (didRun.current) return; didRun.current = true; — then your write logic. This ensures the write only happens once even in StrictMode.
Should I remove StrictMode to fix useEffect running twice?+
No. StrictMode is surfacing a real problem — your effect is not cleanup-safe. Removing it hides the bug without fixing it, and the bug may still cause issues in production when components unmount and remount (e.g. navigating away and back).

Need Expert Help?

We Build Production-Grade Next.js Apps

Softplix builds full-stack Next.js applications. Dealing with React hook issues or SSR complexity? We can help.

Talk to an Engineer