Question · JavaScript and React course · Module 11: Data Fetching and APIs

Stale Closures in useEffect

How do you solve the stale closure problem in useEffect, where setCount(count + 1) always sets the same value?

Answer options

  • Use useRef instead of useState
  • Use a callback in setState: setCount(prev => prev + 1), which receives the current value
  • Add count to the useEffect dependency array
  • Use a global variable instead of state

You can check the correct answer by solving this task in the CodeWorlds game.