Course contentsShow
← React
Lesson 402 of 2,39611. useState Patterns and PitfallsFree lesson

Stale Props in Async Callbacks

How props captured in async functions become stale and patterns to access current prop values.

Stale Props in Async Callbacks

You'll learn how props captured in async functions can become outdated and how to ensure you're working with current values.

The Problem: Props Get Captured Like State

Just like state values, props are also captured by closures when you use them in async callbacks. If a parent component passes new props while an async operation is pending, your callback will still reference the old prop values from when it was created.

function UserProfile({ userId }) {
  const [data, setData] = useState(null);

  const loadUser = async () => {
    await fetchUser(userId); // This userId is captured!
    // If userId prop changed during the fetch, we're using stale data
    setData(result);
  };

  // ...
}

If userId changes from 5 to 10 while fetchUser is running, the callback still thinks userId is 5.

Solutions: Access Current Props

Pattern 1: Use useEffect with dependencies

useEffect(() => {
  let ignore = false;
  
  fetchUser(userId).then(result => {
    if (!ignore) setData(result);
  });
  
  return () => { ignore = true; }; // Cleanup cancels stale requests
}, [userId]); // Re-run when userId changes

Pattern 2: Use useRef for the latest value

const userIdRef = useRef(userId);
userIdRef.current = userId; // Always current

const loadUser = async () => {
  const result = await fetchUser(userIdRef.current); // Latest value
  setData(result);
};

The ref pattern gives you an escape hatch to always read the current prop, bypassing closure capture.

Key Takeaway: Props captured in async callbacks become stale just like state—use cleanup flags in useEffect or refs to access current values and prevent race conditions with outdated props.