React Stale Closure Bug: Understanding State Updates

🚨 The React bug that shows stale data Your API returns updated data. But your UI still shows old values. Why does this happen? The culprit is often a stale closure. Example: function Counter() { const [count, setCount] = useState(0) useEffect(() => { setInterval(() => { console.log(count) }, 2000) }, []) } You might expect the console to print: 0 1 2 3 But it prints: 0 0 0 0 Why? Because the interval captures the initial value of "count". This is called a stale closure. The function inside "setInterval" still uses the old state value. 💡 One fix is using a functional update. setCount(prev => prev + 1) Or storing the latest value with "useRef". Good React engineers don't just manage state. They understand how closures affect state updates. #reactjs #frontend #javascript #softwareengineering #webdevelopment

  • diagram

To view or add a comment, sign in

Explore content categories