Hackforge Academy

Category: react

What Is a Stale Closure?

Published on 27 Oct 2026

Explanation

A closure captures values from the render in which it was created. If a callback keeps running later without being updated, it may read older state or props.

Code:

useEffect(() => {
  const id = setInterval(() => {
    console.log(count); // Captures the count from this render
  }, 1000);
  return () => clearInterval(id);
}, []);

Explanation

When the next state depends on the previous state, use the functional updater form. React supplies the latest state value to the updater.

Code:

useEffect(() => {
  const id = setInterval(() => {
    setCount((current) => current + 1);
  }, 1000);
  return () => clearInterval(id);
}, []);

Explanation

If an effect needs the current value of a prop or state variable, include it in the dependency array. React will clean up and rerun the effect when that value changes.

Code:

useEffect(() => {
  const id = setInterval(() => {
    console.log(count);
  }, 1000);
  return () => clearInterval(id);
}, [count]);

Explanation

A ref can hold a mutable latest value for a long-lived callback without recreating the callback. Use this pattern carefully and prefer normal dependencies when they express the intended synchronization.

Code:

const latestCount = useRef(count);

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

useEffect(() => {
  const id = setInterval(() => console.log(latestCount.current), 1000);
  return () => clearInterval(id);
}, []);

Explanation

A handler created during a render sees that render's values. This is normally correct; problems arise when the handler is retained by a timer, subscription, or external system longer than expected.

Code:

function Search({ query }) {
  const handleSearch = useCallback(() => {
    runSearch(query);
  }, [query]);

  useEffect(() => {
    registerSearchHandler(handleSearch);
    return () => unregisterSearchHandler(handleSearch);
  }, [handleSearch]);

  return null;
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community