React useCallback Causing Infinite Loop— Re-render Cycle Fixed [2026]
Also covers: useEffect dependency cycle · functional setState · useReducer escape hatch · useRef stable callback pattern
⚡ The Infinite Loop
// Infinite re-render cycle:
// count changes → new fetchData ref → useEffect runs → setCount → repeat
const fetchData = useCallback(async () => {
const data = await api.get(`/items?page=${count}`)
setCount(c => c + 1) // updates count
}, [count]) // depends on count
useEffect(() => {
fetchData() // runs when fetchData changes
}, [fetchData]) // fetchData changes every render → infinite loop✅ The cycle: state → callback → effect → state
// Option 1: remove callback from effect deps (if safe)
// Option 2: use setState(prev => ...) to avoid closing over state
// Option 3: use useReducer — dispatch is always stableWhy useCallback Causes Infinite Re-render Loops
The infinite loop has a four-step cycle. Step 1: your useCallback depends on state. Step 2: when state updates, a new function reference is created. Step 3: useEffect sees the new function reference as a changed dep and runs. Step 4: the effect updates state, restarting the cycle.
The fix is to break one link in the chain. You have three reliable options: remove the callback from the effect's deps, use setState's functional updater form to avoid closing over state, or use useReducer whose dispatch is always stable.
Remove the Callback from useEffect Deps
Quickest fix — when the callback itself never changes logicIf the callback is defined inside the component but its logic doesn't actually change between renders, you can safely omit it from the effect's dependency array. Disable the ESLint warning with a comment and document why.
function DataFetcher({ userId }: { userId: string }) {
const [data, setData] = useState(null)
// This callback only needs to run when userId changes
const fetchUserData = useCallback(async () => {
const result = await api.get(`/users/${userId}`)
setData(result)
}, [userId]) // only depends on userId — stable between userId changes
useEffect(() => {
fetchUserData()
// eslint-disable-next-line react-hooks/exhaustive-deps
// fetchUserData is stable while userId is the same — safe to omit
}, [userId]) // ✅ use the primitive dep directly instead of the function
return <div>{data?.name}</div>
}
// Even simpler — skip useCallback entirely and inline the fetch:
useEffect(() => {
async function load() {
const result = await api.get(`/users/${userId}`)
setData(result)
}
load()
}, [userId]) // ✅ no callback reference — just the primitive depDefining the async function inside useEffect and calling it immediately is the cleanest pattern. It avoids both useCallback and the dep cycle.
Use the Functional Updater Form of setState
Callback reads state to produce next stateIf your callback reads state only to compute the next state value, use setState(prev => nextValue) . The functional form receives the previous state as an argument — no need to close over state in the callback, no need to include state in deps.
// ❌ Closes over count — count must be in deps → cycle
const increment = useCallback(() => {
setCount(count + 1) // reads count from closure
}, [count]) // count dep → new ref every render
// ✅ Functional updater — no need to close over count
const increment = useCallback(() => {
setCount(prev => prev + 1) // gets prev from React — count not needed in closure
}, []) // stable empty deps — no cycle
// ✅ Same pattern for complex state
const addItem = useCallback((item: Item) => {
setItems(prev => [...prev, item]) // prev provided by React
}, []) // stable — no items dep needed
// ✅ Pattern for toggling
const toggleOpen = useCallback(() => {
setIsOpen(prev => !prev)
}, [])Use useReducer to Break Callback-State Cycles
Complex state interactions — the canonical escape hatchuseReducer's dispatch function is always referentially stable — it never changes between renders. Replace state + setState with useReducer to get a stable action dispatcher that you can safely put in any dependency array.
import { useReducer, useCallback, useEffect } from "react"
type State = { count: number; data: any[]; loading: boolean }
type Action =
| { type: "INCREMENT" }
| { type: "SET_DATA"; payload: any[] }
| { type: "SET_LOADING"; payload: boolean }
function reducer(state: State, action: Action): State {
switch (action.type) {
case "INCREMENT":
return { ...state, count: state.count + 1 }
case "SET_DATA":
return { ...state, data: action.payload, loading: false }
case "SET_LOADING":
return { ...state, loading: action.payload }
default:
return state
}
}
function PaginatedList() {
const [state, dispatch] = useReducer(reducer, { count: 0, data: [], loading: false })
// ✅ dispatch is stable — safe in deps, no cycle
const fetchPage = useCallback(async (page: number) => {
dispatch({ type: "SET_LOADING", payload: true })
const data = await api.get(`/items?page=${page}`)
dispatch({ type: "SET_DATA", payload: data })
}, []) // empty deps — dispatch is stable, no state closure
useEffect(() => {
fetchPage(state.count)
}, [fetchPage, state.count]) // safe — fetchPage is stable
return (
<div>
{state.data.map(item => <div key={item.id}>{item.name}</div>)}
<button onClick={() => dispatch({ type: "INCREMENT" })}>Next page</button>
</div>
)
}Use useRef to Access Latest Value Without Adding Deps
Event handlers that need latest state without causing re-renderStore the latest version of a callback in a ref. Create a stable callback that reads from the ref. This pattern gives you always-current logic in a never-changing function reference.
import { useCallback, useEffect, useRef } from "react"
function useStableCallback<T extends (...args: any[]) => any>(fn: T): T {
const ref = useRef(fn)
// Keep the ref current without triggering re-renders
useEffect(() => {
ref.current = fn
})
// Return a stable callback that delegates to the latest ref
return useCallback((...args: any[]) => ref.current(...args), []) as T
}
// Usage — the callback is always stable regardless of what it closes over
function SearchBox({ onSearch, filters }: { onSearch: (q: string) => void; filters: object }) {
// Even though onSearch or filters might change, handleSearch is always stable
const handleSearch = useStableCallback((query: string) => {
onSearch(query)
console.log("Filters at search time:", filters) // always latest filters
})
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.key === "Enter") handleSearch((e.target as HTMLInputElement).value)
}
window.addEventListener("keypress", handler)
return () => window.removeEventListener("keypress", handler)
}, [handleSearch]) // handleSearch is always stable — effect runs once
}Stabilise Callbacks Passed as Props to Child Effects
Child useEffect runs every render because parent callback changedIf a parent passes an unstable callback as a prop to a child that uses it in useEffect, wrap it in useCallback in the parent. If the parent itself doesn't change the logic, use an empty dep array.
// ❌ Parent creates new function every render
function Parent() {
const [count, setCount] = useState(0)
// new reference every render — child effect runs every render
const onScroll = (y: number) => { console.log("scroll", y, count) }
return <ScrollTracker onScroll={onScroll} />
}
// ✅ Stabilise with useCallback
function Parent() {
const [count, setCount] = useState(0)
const onScroll = useCallback((y: number) => {
// use functional updater if you need to read count
setCount(prev => {
console.log("scroll at count:", prev, y)
return prev
})
}, []) // stable — no closure over count needed
return <ScrollTracker onScroll={onScroll} />
}
// Child — uses onScroll in useEffect
function ScrollTracker({ onScroll }: { onScroll: (y: number) => void }) {
useEffect(() => {
const handler = () => onScroll(window.scrollY)
window.addEventListener("scroll", handler)
return () => window.removeEventListener("scroll", handler)
}, [onScroll]) // only re-attaches when onScroll changes reference
}Prevention
- Define async functions inside useEffect to avoid useCallback+useEffect dep cycles entirely
- Use setState(prev => next) instead of setState(state + x) — removes state from callback deps
- Use useReducer for complex state — dispatch is always stable, breaks any callback-state cycle
- Enable exhaustive-deps ESLint rule — it catches missing deps but not all cycle patterns
- Only use useCallback when the function is a dep of useEffect/useMemo or prop of React.memo child
- Use the useRef stable callback pattern for event handlers that need always-current values
Frequently Asked Questions
Why does useCallback cause an infinite loop with useEffect?+−
Should I wrap every function with useCallback?+−
What is the functional updater form of setState?+−
When should I use useReducer instead of useState with useCallback?+−
Can I use useRef to avoid adding a dep to useCallback?+−
What is the difference between useCallback and useMemo for functions?+−
Need Expert Help?
We Build Production React Applications
Softplix engineers build React apps with clean hook architecture, performance optimisation, and zero infinite loop bugs. Let us help.
Talk to an Engineer