useEffect Clean Up Correctly :👈 👉:useContext Without Prop Drilling

How to Avoid Stale State in React Hooks

How to Avoid Stale State in React Hooks

1. What Is Stale State in React?

Stale state occurs when a function uses an outdated value of state or props instead of the latest value.

In React, each render has its own state snapshot. Functions created during that render capture the values available at that time. If a callback executes later, it may still use those older values.

Stale state commonly occurs in:

  • setTimeout() and setInterval().
  • Event handlers and event listeners.
  • useEffect() callbacks.
  • Asynchronous API requests.
  • Callbacks passed to child components.
  • Functions created with useCallback().

2. Example: Stale State with useState

Consider a counter that schedules an increment after one second.

Incorrect Example

import { useState } from "react";
function Counter() {
    const [count, setCount] = useState(0);
    function incrementLater() {
        setTimeout(() => {
            setCount(count + 1);
        }, 1000);
    }
    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={incrementLater}>
                Increment Later
            </button>
        </div>
    );
}
export default Counter;

What can go wrong?

  1. The counter starts at 0.
  2. You click the button twice before either timeout executes.
  3. Both callbacks captured count = 0.
  4. Both callbacks call setCount(0 + 1).
  5. The final count is 1 instead of 2.

The problem is that both callbacks use the same older state snapshot.

Correct Example: Use a Functional State Update

import { useState } from "react";
function Counter() {
    const [count, setCount] = useState(0);
    function incrementLater() {
        setTimeout(() => {
            setCount(previousCount => previousCount + 1);
        }, 1000);
    }
    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={incrementLater}>
                Increment Later
            </button>
        </div>
    );
}
export default Counter;

Why does this work?

The functional updater receives the latest state value used by React when processing the update. Each increment is calculated from the previous state rather than from the state snapshot captured by the timeout.

Important: When the next state depends on the previous state, prefer a functional updater.

// Avoid when count may be stale
setCount(count + 1);
// Prefer when the next value depends on the previous value
setCount(previousCount => previousCount + 1);

3. Stale State in useEffect with setInterval

A common stale-state problem occurs when an interval is created inside useEffect().

Incorrect Example

import { useEffect, useState } from "react";
function Timer() {
    const [count, setCount] = useState(0);
    useEffect(() => {
        const intervalId = setInterval(() => {
            setCount(count + 1);
        }, 1000);
        return () => {
            clearInterval(intervalId);
        };
    }, []);
    return <p>Count: {count}</p>;
}
export default Timer;

Problem:

The empty dependency array means the effect runs when the component mounts. The interval callback captures the initial value of count, which is 0. It repeatedly attempts to set the count to 1.

Solution 1: Use a Functional State Update

import { useEffect, useState } from "react";
function Timer() {
    const [count, setCount] = useState(0);
    useEffect(() => {
        const intervalId = setInterval(() => {
            setCount(previousCount => previousCount + 1);
        }, 1000);
        return () => {
            clearInterval(intervalId);
        };
    }, []);
    return <p>Count: {count}</p>;
}
export default Timer;

This is usually the simplest solution when the update depends only on the previous state. The interval can remain active without needing to recreate it after every count change.

Solution 2: Include the State in the Dependency Array

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

This version cleans up the previous interval and creates a new one whenever count changes. It can work, but it repeatedly resets the interval. For a simple counter, the functional updater is generally preferable.

4. Stale State in useEffect Dependencies

React effects can capture outdated props or state when their dependency arrays omit reactive values that the effect uses.

Incorrect Example

import { useEffect, useState } from "react";
function Greeting() {
    const [name, setName] = useState("Alex");
    useEffect(() => {
        const intervalId = setInterval(() => {
            console.log("Hello", name);
        }, 2000);
        return () => {
            clearInterval(intervalId);
        };
    }, []);
    return (
        <div>
            <p>Name: {name}</p>
            <button onClick={() => setName("Sam")}>
                Change Name
            </button>
        </div>
    );
}

Problem: The interval continues to log Alex, even after the name changes to Sam, because the effect captured the initial name.

Solution 1: Add the Missing Dependency

useEffect(() => {
    const intervalId = setInterval(() => {
        console.log("Hello", name);
    }, 2000);
    return () => {
        clearInterval(intervalId);
    };
}, [name]);

Now React cleans up and recreates the interval whenever name changes. The callback uses the latest name.

Use this approach when the external synchronization should be restarted when the value changes.

Solution 2: Use a Functional Updater When Appropriate

If an effect only needs to calculate a new state from its previous value, use a functional updater instead of reading the state variable directly.

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

A functional updater does not solve every stale-closure problem. It is specifically useful when calculating the next state from the previous state.

5. Stale State in Event Listeners

Browser event listeners can also retain values from the render in which they were registered.

Incorrect Example

import { useEffect, useState } from "react";
function WindowWidthExample() {
    const [count, setCount] = useState(0);
    useEffect(() => {
        function handleResize() {
            console.log("Current count:", count);
        }
        window.addEventListener("resize", handleResize);
        return () => {
            window.removeEventListener("resize", handleResize);
        };
    }, []);
    return (
        <button onClick={() => setCount(value => value + 1)}>
            Count: {count}
        </button>
    );
}

The resize listener captures the initial value of count. Clicking the button updates the displayed count, but resizing the window still logs the old value.

Solution 1: Re-register the Listener When the Value Changes

useEffect(() => {
    function handleResize() {
        console.log("Current count:", count);
    }
    window.addEventListener("resize", handleResize);
    return () => {
        window.removeEventListener("resize", handleResize);
    };
}, [count]);

This is appropriate when the listener needs to use the latest count and re-registering it when the count changes is acceptable.

Solution 2: Use a Ref for the Latest Value

If you need to keep one event listener registered while allowing it to read the latest value, a ref can store that value.

import { useEffect, useRef, useState } from "react";
function WindowWidthExample() {
    const [count, setCount] = useState(0);
    const countRef = useRef(count);
    useEffect(() => {
        countRef.current = count;
    }, [count]);
    useEffect(() => {
        function handleResize() {
            console.log("Current count:", countRef.current);
        }
        window.addEventListener("resize", handleResize);
        return () => {
            window.removeEventListener("resize", handleResize);
        };
    }, []);
    return (
        <button onClick={() => setCount(value => value + 1)}>
            Count: {count}
        </button>
    );
}
export default WindowWidthExample;

Why does this work?

  • countRef retains the same ref object across renders.
  • The effect updates countRef.current when count changes.
  • The listener reads countRef.current when the resize event occurs.
  • Changing a ref's current property does not itself trigger a render.

Note: The ref is updated by an effect, so there can be a short interval before that effect runs. If exact synchronization with each committed render is important, consider whether an effect event or a different event-handling design is more suitable.

6. Stale State in useCallback

useCallback() caches a function between renders while its dependencies remain unchanged. If a callback uses state but omits that state from its dependency array, it can keep using an old value.

Incorrect Example

import { useCallback, useState } from "react";
function Profile() {
    const [name, setName] = useState("Alex");
    const showName = useCallback(() => {
        console.log(name);
    }, []);
    return (
        <div>
            <p>Name: {name}</p>
            <button onClick={() => setName("Sam")}>
                Change Name
            </button>
            <button onClick={showName}>
                Show Name
            </button>
        </div>
    );
}

Problem: The callback captures the initial name because the dependency array is empty. Clicking Show Name continues to log Alex.

Correct Example

const showName = useCallback(() => {
    console.log(name);
}, [name]);

Now the callback is recreated when name changes, so it uses the latest value.

Important: Do not use an empty dependency array automatically. Include every reactive value used by the callback unless you deliberately use a different pattern that avoids the dependency.

7. Stale State in Asynchronous Functions

Asynchronous functions can capture state before an await and continue using that captured value after the asynchronous operation finishes.

Example

async function saveProfile() {
    const currentName = name;
    await saveToServer();
    console.log("Saved profile for:", currentName);
}

If name changes while saveToServer() is running, currentName still contains the value from when the function started.

This is not always a bug. Sometimes you want to save the exact value that the user submitted. The important question is whether the operation should use the value at the time it started or the latest value when it finishes.

Solution 1: Capture the Submitted Value Intentionally

async function saveProfile() {
    const submittedName = name;
    await saveToServer(submittedName);
    console.log("Submitted profile for:", submittedName);
}

This approach is correct when the operation should use the name that was submitted, even if the user changes the input while the request is running.

Solution 2: Read the Latest State After Awaiting

If the function needs the latest state after the asynchronous operation, a ref can provide a current-value reference.

import { useEffect, useRef, useState } from "react";
function Profile() {
    const [name, setName] = useState("Alex");
    const nameRef = useRef(name);
    useEffect(() => {
        nameRef.current = name;
    }, [name]);
    async function handleSave() {
        await saveToServer();
        console.log("Latest name:", nameRef.current);
    }
    return (
        <div>
            <input
                value={name}
                onChange={event => setName(event.target.value)}
            />
            <button onClick={handleSave}>
                Save
            </button>
        </div>
    );
}
async function saveToServer() {
    // Example asynchronous operation.
}

This example demonstrates reading the latest name after the asynchronous operation. If the server must save that latest name too, read the ref at the appropriate time and explicitly pass the value to the save operation.

For production code, also consider request cancellation, duplicate submissions, and whether the response belongs to the most recent operation.

8. Avoiding Stale State in Search and API Requests

Search components can have a related problem: a slower response for an earlier search may arrive after a newer response and overwrite the latest results.

This is often called a race condition. It is related to asynchronous timing, but it is not exactly the same as a stale closure.

Example: Ignore Outdated Requests

import { useEffect, useState } from "react";
function UserSearch({ query }) {
    const [users, setUsers] = useState([]);
    const [error, setError] = useState(null);
    useEffect(() => {
        let ignore = false;
        async function fetchUsers() {
            try {
                setError(null);
                const response = await fetch(
                    `/api/users?query=${encodeURIComponent(query)}`
                );
                if (!response.ok) {
                    throw new Error("Failed to fetch users");
                }
                const data = await response.json();
                if (!ignore) {
                    setUsers(data);
                }
            } catch (err) {
                if (!ignore) {
                    setError(err.message);
                }
            }
        }
        fetchUsers();
        return () => {
            ignore = true;
        };
    }, [query]);
    if (error) {
        return <p>Error: {error}</p>;
    }
    return (
        <ul>
            {users.map(user => (
                <li key={user.id}>{user.name}</li>
            ))}
        </ul>
    );
}
export default UserSearch;

How it works:

  • The effect runs whenever query changes.
  • Each request has its own ignore flag.
  • When the effect is cleaned up, its flag is set to true.
  • An outdated request cannot update the component's results or error state.

For network requests, AbortController is another useful option because it can cancel the previous fetch when a new query arrives or the component unmounts. Ignoring outdated responses and aborting requests solve related but distinct concerns.

9. When Should You Use useRef to Avoid Stale State?

A ref is useful when a callback needs to access the latest value without causing a render whenever that value changes.

Common use cases include:

  • Long-lived event listeners.
  • Intervals and timeouts.
  • WebSocket callbacks.
  • Third-party event subscriptions.
  • Tracking the latest callback or value for an external API.

Example:

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

Later, a long-lived callback can read:

console.log(latestCount.current);

Do not replace every state variable with a ref. If a value is displayed in the UI and changing it should update the screen, use state. Ref updates do not trigger renders.

10. useEffectEvent in Modern React

In React versions that support useEffectEvent, it can help separate an effect's synchronization logic from callback logic that needs to read the latest props or state without making those values dependencies of the effect.

For example, imagine connecting to a chat room while a notification should use the latest theme. Changing the theme should update the notification behavior without necessarily reconnecting the chat room.

import { useEffect, useEffectEvent } from "react";
function ChatRoom({ roomId, theme }) {
    const onConnected = useEffectEvent(() => {
        showNotification("Connected!", theme);
    });
    useEffect(() => {
        const connection = createConnection(roomId);
        connection.on("connected", () => {
            onConnected();
        });
        connection.connect();
        return () => {
            connection.disconnect();
        };
    }, [roomId]);
    return null;
}

Key points:

  • The effect reconnects when roomId changes.
  • The effect event reads the latest theme when invoked.
  • useEffectEvent is intended for event-like logic originating from effects, not as a general replacement for event handlers or dependency arrays.
  • It is available only in React versions that support it. Check your installed React version and official documentation before using it.

If your React version does not support useEffectEvent, use the dependency array, functional state updater, or ref-based approach appropriate to the problem.

11. Quick Comparison: Which Solution Should You Use?

Problem Recommended Solution Reason
Incrementing or updating state based on its previous value Functional state updater Uses the previous state supplied by React.
Effect needs to synchronize with a changing value Add the value to the dependency array Keeps the effect synchronized with its reactive inputs.
Long-lived listener needs the latest value Ref or an appropriate Effect Event Lets the callback access current values without repeatedly registering the listener, when suitable.
useCallback uses changing state Add the missing dependency Ensures the callback is recreated when its reactive inputs change.
Older API request returns after a newer request Cancel or ignore outdated requests Prevents obsolete responses from overwriting current results.
Async operation should use the value submitted at the start Capture the value intentionally Preserves the submitted snapshot instead of silently switching to a later value.

12. Common Mistakes to Avoid

  • Using an empty dependency array automatically: An empty array is appropriate only when the effect does not need to react to changing values captured from the component scope, or when a deliberate alternative pattern is used.
  • Ignoring the React Hooks dependency warning: Do not silence the linter without understanding why the dependency is unnecessary or how the code avoids the stale closure.
  • Using state variables in delayed updates unnecessarily: Use a functional updater when the next state depends on the previous state.
  • Using refs for everything: Refs do not trigger rendering and should not replace state that drives the UI.
  • Assuming useCallback fixes stale state automatically: It does not. Its dependencies must be correct.
  • Adding every state variable to every effect without considering the design: Dependencies should reflect the effect's reactive inputs. If a value should not trigger resynchronization, reconsider the effect's structure or use a suitable alternative.
  • Assuming every stale closure is a bug: A function intentionally capturing the value at the time an operation starts can be correct.
  • Forgetting cleanup: Clear timers and remove event listeners when their effects are cleaned up.
  • Confusing stale closures with race conditions: A stale closure reads an old captured value; a race condition occurs when competing asynchronous operations complete in an unexpected order. An application can have either or both.

13. Best Practices

  1. Use functional state updates whenever the next state depends on the previous state.
  2. Declare all reactive dependencies used by an effect or callback.
  3. Use useEffect to synchronize with external systems, and provide cleanup where necessary.
  4. Use refs when a long-lived callback needs a current value without triggering a render.
  5. Consider useEffectEvent when supported and when its intended effect-event use case fits.
  6. Handle asynchronous operations deliberately: decide whether to use the submitted value or the latest value.
  7. Cancel or ignore outdated requests when results can arrive out of order.
  8. Keep the React Hooks ESLint rules enabled.
  9. Test rapid clicks, quick input changes, delayed responses, component unmounts, and timer cleanup.
  10. Prefer the simplest correct solution. Do not add refs or memoization unless the problem requires them.

14. Interview Questions and Answers

Q1. What is stale state in React?

Stale state occurs when a callback reads a state or prop value captured during an earlier render instead of the value expected at the time the callback executes.

Q2. Why does stale state happen in useEffect?

An effect's callback closes over the values from the render in which the effect was created. If the effect is not resynchronized when a required reactive value changes, the callback can continue using an older value.

Q3. How does a functional state updater help?

A functional updater, such as setCount(previousCount => previousCount + 1), calculates the next state from the previous state supplied by React. This avoids depending on a potentially stale state variable captured by the callback.

Q4. Does useCallback prevent stale state?

No. useCallback caches a function while its dependencies remain unchanged. If a dependency is missing, the cached callback can keep using an old value.

Q5. What is the difference between useState and useRef for this problem?

useState stores values that participate in rendering. Updating state triggers a render when React determines the value has changed. useRef stores a persistent mutable value that can be read by callbacks without triggering a render when its current property changes.

Q6. Should you always add state variables to the useEffect dependency array?

You should include the reactive values that the effect uses. If including a value causes unwanted resynchronization, restructure the effect or use a suitable pattern rather than simply omitting the dependency.

Q7. How can stale state occur in setInterval?

The interval callback may capture a state value from the render in which the interval was created. If it uses that captured value in every update, it may repeatedly calculate the same result. A functional updater is often the simplest fix.

Q8. How do you prevent outdated API responses from overwriting new results?

Cancel outdated requests where possible, or ignore responses from requests that are no longer relevant. This prevents older asynchronous operations from overwriting newer results.

Q9. Is stale state the same as a race condition?

No. Stale state is about a callback reading an old captured value. A race condition is about the ordering of concurrent or asynchronous operations. Both can occur in the same component.

Q10. When is a stale closure intentional?

It is intentional when an operation must use the values that existed when it started, such as saving the exact form value the user submitted. The important part is deciding which snapshot the operation should use.

15. Summary

Stale state is a common React Hooks issue caused by callbacks retaining values from earlier renders. The correct solution depends on why the callback needs the value.

  • Functional updater: Use when the next state depends on the previous state.
  • Dependency array: Use when an effect or callback should respond to changes in a reactive value.
  • useRef: Use when a long-lived callback needs access to a current value without triggering a render.
  • useEffectEvent: Use when supported and appropriate for effect-originated event logic that needs current props or state without resynchronizing the effect for those values.
  • Request cancellation or ignoring outdated responses: Use when asynchronous operations can complete out of order.

Most important rule: Do not automatically use refs or memoization to fix stale state. First identify whether you need the previous state, a changing reactive value, the latest value, or the original value captured when an operation began.

🔙
useEffect Clean Up Correctly :👈 👉:useContext Without Prop Drilling

Comments and Discussion