useEffect Running Twice React 18— Fixed [2026]
Also covers: API called twice · StrictMode double render · fetch running twice in Next.js
⚡ The Real Fix — Add a Cleanup Function
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?
// 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 type | Correct cleanup |
|---|---|
| fetch / API call | AbortController → abort() in cleanup |
| EventListener | removeEventListener in cleanup |
| WebSocket / SSE | close() the connection in cleanup |
| setInterval / setTimeout | clearInterval / clearTimeout in cleanup |
| Database write / side effect | Ref flag to prevent second execution |
Add a Cleanup Function — The Correct Approach
Every useEffect that does async work needs thisEvery useEffect that starts an asynchronous operation should return a cleanup function that cancels or ignores the result when the component unmounts.
// ✅ 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()
}, [])Deduplicate API Calls With AbortController
API called twice — most painful symptomWhen 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.
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 }
}Prevent Duplicate Side Effects With a Ref
Database writes, analytics, one-time operationsFor side effects that must only run once — analytics events, database writes, initialisation — use a ref to track whether it has already run.
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.
Remove StrictMode — Use Only as Last Resort
Not recommended — hides the real problemYou 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.
// ❌ 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.
Use a Data Fetching Library
Best long-term solution — handles deduplication automaticallyLibraries like SWR and TanStack Query handle deduplication, caching, and race conditions automatically. They are immune to the StrictMode double-invoke problem.
npm install swr
# or
npm install @tanstack/react-queryimport 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
}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>
}Analytics and Tracking — Fire Once Only
Page view events firing twiceimport { 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
- Every fetch in useEffect needs an AbortController — always
- Every event listener added must be removed in the cleanup function
- Every interval and timeout must be cleared in cleanup
- Every subscription (WebSocket, SSE, Redux) must be closed/unsubscribed
- Use useRef flag for truly one-time side effects like analytics
- Consider SWR or TanStack Query — they handle all of this automatically
Frequently Asked Questions
Why does useEffect run twice in React 18?+−
Does useEffect run twice in production?+−
How do I make useEffect run only once in React 18?+−
How do I stop useEffect from fetching data twice?+−
useEffect running twice is causing duplicate database writes — how to fix?+−
Should I remove StrictMode to fix useEffect running twice?+−
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