Skip to content

useEffect infinite loop

Quick summary

Your useEffect updates state on every run and its dependency array causes it to run after every render — creating an infinite loop.

Why this happens

  • The effect updates state unconditionally and the dependency array includes the state it updates

  • The dependency array is missing or contains an object/array that is recreated every render, always looking new

  • The effect sets state based on a value that changes on every render, like a new object or array reference

Minimal example

✗ Broken code
function Component({ data }) {
  const [items, setItems] = useState([]);
  useEffect(() => {
    setItems(data.map(d => d.name)); // updates every render
  }, [data]); // data is new array each render = infinite loop
}
✓ Fixed code
function Component({ data }) {
  const [items, setItems] = useState([]);
  const names = useMemo(() => data.map(d => d.name), [data]);
  useEffect(() => {
    setItems(names);
  }, [names]); // names is stable unless data changes
}

Memoizing the derived value with useMemo keeps its reference stable across renders, so the effect only runs when data actually changes.

How to diagnose

  • Add console.log inside the effect to see if it fires repeatedly without stopping

  • Check the dependency array for values that change on every render (new objects, arrays, or functions)

  • Use React DevTools Profiler to detect continuous re-renders and identify the effect causing the loop

How to fix

  • Add a condition to only update state when the value actually changes: if (newVal !== val) setVal(newVal)

  • Memoize the dependency with useMemo or useCallback so its reference stays stable across renders

  • Remove the changing dependency from the array or split the effect into one that runs once and one that depends on stable values

How to prevent

  • Always think carefully about which values the effect depends on and memoize unstable references

  • Use the eslint-plugin-react-hooks exhaustive-deps rule to catch missing or extra dependencies

Related Resources

Related Glossary

Related Lessons

← Back to language