DeployU
Interviews / Frontend Engineering / This `useEffect` is logging a stale value. How do you fix its dependency array?

Questions

This `useEffect` is logging a stale value. How do you fix its dependency array?

debugging Hooks & Patterns Interactive Quiz Code Examples
Wrong Approach

Just remove the setInterval and use a different approach.

Right Approach

This is a classic stale closure bug. The empty dependency array means the effect captures the initial count (0) forever. The fix is to include count in the dependency array:

Why It’s Stale:

  • Empty [] = effect runs once on mount
  • The setInterval callback “closes over” count = 0
  • Even when state updates, the callback still sees count = 0

The Fix: Add count to the dependency array. The effect will re-run when count changes, recreating the interval with the fresh value.

Counter - Fix the Stale Closure
Your Code
import React, { useState, useEffect } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    // THE BUG: Captures initial count (0) due to empty []
    const intervalId = setInterval(() => {
      console.log(`Count from useEffect: ${count}`);
    }, 2000);

    return () => clearInterval(intervalId);
  }, []); // ← Should include count

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => setCount(c => c + 1)}>Increment</button>
      <p>Check console - it always logs 0!</p>
    </div>
  );
}
Click "Run Code" to see output...
Click "Run Code" to see test results...

The Solution

useEffect(() => {
  const intervalId = setInterval(() => {
    console.log(`Count from useEffect: ${count}`);
  }, 2000);

  return () => clearInterval(intervalId); // Cleanup is crucial!
}, [count]); // Re-run when count changes

The cleanup function clears the old interval before creating a new one, preventing multiple intervals from stacking up.

Practice Question

What is the consequence of omitting a dependency from a useEffect's dependency array when that dependency is used inside the effect?