React Closures Cause Stale State Bugs

🧠 React Concept: Why Closures Cause “Stale State” Bugs Sometimes React code looks correct… but the behavior is confusing. Example 👇 function Counter() { const [count, setCount] = React.useState(0); function handleClick() { setTimeout(() => { console.log(count); }, 2000); } return ( <div> <button onClick={() => setCount(count + 1)}>Increment</button> <button onClick={handleClick}>Log Count</button> </div> ); } Now imagine this: 1️⃣ Click Increment → count becomes 1 2️⃣ Click Log Count 3️⃣ Click Increment again → count becomes 2 After 2 seconds… The console prints: 1 Not 2. 🤔 Why? Because of JavaScript closures. When handleClick runs, it captures the value of count at that moment. React updates state later, but the closure still remembers the old value. ✅ Correct Solution Use a ref to access the latest state. const countRef = useRef(count); useEffect(() => { countRef.current = count; }, [count]); setTimeout(() => { console.log(countRef.current); }, 2000); Now the value stays up-to-date. 🎯 Key Takeaway Many React bugs are not React problems. They are JavaScript closure problems. Understanding this saves hours of debugging. #ReactJS #JavaScript #FrontendDevelopment #ReactHooks #WebDevelopment #CodingTips #LearningInPublic

To view or add a comment, sign in

Explore content categories