React useEffect Stale Closure Bug Fix

𝐓𝐫𝐢𝐜𝐤𝐲 𝐑𝐞𝐚𝐜𝐭 𝐮𝐬𝐞𝐄𝐟𝐟𝐞𝐜𝐭 𝐒𝐭𝐚𝐥𝐞 𝐂𝐥𝐨𝐬𝐮𝐫𝐞 𝐁𝐮𝐠 🚨 Many developers use useEffect daily… but get confused when bugs appear unexpectedly. Question: Why does this code log the wrong value? Example 👇 import React, { useState, useEffect } from "react"; export default function App() { const [count, setCount] = useState(0); useEffect(() => { const id = setInterval(() => { console.log(count); }, 1000); return () => clearInterval(id); }, []); return ( <> <button onClick={() => setCount(count + 1)}> Count: {count} </> ); } What’s the issue? 🤔 Even after clicking the button, console always logs: 0 Why? Because of stale closure. useEffect runs only once (empty dependency array []) and the interval callback captures the initial value of count (0). So it never sees updated state. Correct solution ✅ useEffect(() => { const id = setInterval(() => { console.log(count); }, 1000); return () => clearInterval(id); }, [count]); Best practice ⭐ Use useRef to always get latest value without re-running effect import React, { useState, useEffect, useRef } from "react"; export default function App() { const [count, setCount] = useState(0); const countRef = useRef(count); useEffect(() => { countRef.current = count; }, [count]); useEffect(() => { const id = setInterval(() => { console.log(countRef.current); }, 1000); return () => clearInterval(id); }, []); return ( <> <button onClick={() => setCount(count + 1)}> Count: {count} </> ); } Tip for Interview ⚠️ Always be careful with dependency arrays in useEffect. Wrong dependencies can lead to stale data bugs. Good developers fix bugs. Great developers understand why they happen. #ReactJS #useEffect #JavaScript #Closures #FrontendDeveloper #WebDevelopment #ReactInterview #CodingInterview #ReactHooks

  • Tricky React useEffect Stale Closure Bug

To view or add a comment, sign in

Explore content categories