Why Your React App Is Lying to You — The Truth About Stale State 🔥

Sahil SagvekarSahil Sagvekar
2 min read

👀 Imagine This:

You click a button, expecting the state to update.
But instead... React silently ignores you.

You console log the value.
It shows the old one.
Again. And again.

Welcome to the dark side of React: stale state.

🤯 The Silent Bug That’s Costing You Hours

If you've ever used useState or useEffect and said:

“Why isn’t this working?! I literally just updated the state!”

You’ve been haunted by stale closures — one of the most misunderstood behaviors in React.

🧠 Let’s Break It Down (Without BS)

const [count, setCount] = useState(0);

const handleClick = () => {
  setTimeout(() => {
    alert(`Count is: ${count}`);
  }, 2000);
};

return <button onClick={handleClick}>Click me</button>;

What You Expect:

"Count is: 1"

What You Get:

"Count is: 0" 😡

Why? Because the closure “remembers” the old count — not the updated one. React doesn’t re-bind count inside setTimeout.

💡 Here’s the Fix (And Why It Works)

Use a function instead of value — or use refs.

const handleClick = () => {
  setTimeout(() => {
    setCount(prev => {
      alert(`Count is: ${prev}`);
      return prev;
    });
  }, 2000);
};

Or use a useRef:

const countRef = useRef(count);

useEffect(() => {
  countRef.current = count;
}, [count]);

const handleClick = () => {
  setTimeout(() => {
    alert(`Count is: ${countRef.current}`);
  }, 2000);
};

🧪 Real World Chaos: This Bug Wrecks…

✅ API debouncing
✅ setInterval in timers
✅ Socket listeners
✅ Background sync
✅ Even useEffect inside custom hooks

99% of “React not working” bugs from juniors = stale closures.
But no one tells you why it happens.

Until now.

🔥 One-Liner Summary:

“In React, functions don’t re-run — they remember. And what they remember can kill your app.”

📢 Call to Arms:

If you’ve ever been gaslit by your own console logs,
you owe it to yourself (and your sanity) to learn closure behavior.

📌 Bookmark this blog.
💬 Share it with your team.
🧠 Remember: “Fresh bugs are always caused by stale state.”

0
Subscribe to my newsletter

Read articles from Sahil Sagvekar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sahil Sagvekar
Sahil Sagvekar