ReactHooksError Fix2026 Updated

React useCallback Causing Infinite Loop— Re-render Cycle Fixed [2026]

Also covers: useEffect dependency cycle · functional setState · useReducer escape hatch · useRef stable callback pattern

January 20267 min readReact 18/19 · TypeScript

⚡ The Infinite Loop

Error
// 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

Break the cycle — 3 approaches
// 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 stable

Why 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.

1

Remove the Callback from useEffect Deps

Quickest fix — when the callback itself never changes logic
2 min

If 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.

Remove stable callback from effect deps
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 dep

Defining the async function inside useEffect and calling it immediately is the cleanest pattern. It avoids both useCallback and the dep cycle.

2

Use the Functional Updater Form of setState

Callback reads state to produce next state
2 min

If 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.

Functional updater removes state from callback 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)
}, [])
3

Use useReducer to Break Callback-State Cycles

Complex state interactions — the canonical escape hatch
5 min

useReducer'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.

useReducer — stable dispatch breaks the cycle
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>
  )
}
4

Use useRef to Access Latest Value Without Adding Deps

Event handlers that need latest state without causing re-render
3 min

Store 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.

useRef stable callback — latest value without dep cycle
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
}
5

Stabilise Callbacks Passed as Props to Child Effects

Child useEffect runs every render because parent callback changed
3 min

If 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 → Child callback stability
// ❌ 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

Frequently Asked Questions

Why does useCallback cause an infinite loop with useEffect?+
The cycle is: useCallback depends on state → state changes → new callback reference → useEffect sees new dep → runs effect → updates state → new callback → repeat. The fix is to break one link in the chain: either remove the callback from useEffect deps, use the functional updater form of setState, or use useReducer.
Should I wrap every function with useCallback?+
No. useCallback is only useful when: the function is passed as a prop to a React.memo child, or the function is a dependency of useEffect/useMemo and you need a stable reference. For event handlers that are not deps or props to memo'd children, useCallback adds overhead without benefit.
What is the functional updater form of setState?+
Instead of setState(state + 1) which requires state as a dependency, use setState(prev => prev + 1). The functional form receives the previous state as an argument, so you don't need to close over state in the callback. This removes state from the dependency array and breaks infinite loops.
When should I use useReducer instead of useState with useCallback?+
Use useReducer when your callback needs to read and update state, causing dependency cycles. useReducer's dispatch function is stable (never changes reference), so you can always include it in dependency arrays without triggering re-renders. This is the canonical escape hatch for complex callback-state interactions.
Can I use useRef to avoid adding a dep to useCallback?+
Yes — this is called the useRef event handler pattern or ref callback pattern. Store the latest version of a function in a ref, then call ref.current() inside your stable callback. The stable callback never changes reference, while always calling the latest version of the function.
What is the difference between useCallback and useMemo for functions?+
useCallback(fn, deps) is equivalent to useMemo(() => fn, deps). Both memoize a value between renders. useCallback is syntactic sugar for the common case of memoizing a function. Use useCallback for functions, useMemo for computed values.

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