HardHooks & Closures💻 Output Question

useEffect deps — effect runs only on relevant changes

💡

Hint

useEffect compares deps shallowly by reference. Same values in a new array still triggers the effect if references differ — this is why objects/arrays as deps cause infinite loops.

What does this output?

// Simulates useEffect dependency tracking
function useEffect(effect, deps) {
  let prevDeps = null;
  return function run(newDeps) {
    const changed = !prevDeps || newDeps.some((d, i) => d !== prevDeps[i]);
    if (changed) {
      effect();
      prevDeps = newDeps;
    }
  };
}

const effectRunner = useEffect(
  () => console.log('effect ran'),
  []
);

effectRunner([1]);     // first run
effectRunner([1]);     // same deps
effectRunner([2]);     // deps changed
effectRunner([2]);     // same again

Correct Output

effect ran
effect ran

Why this output?

Explanation: Effect runs on first call (no prevDeps). Skips when deps are the same [1]===[1]. Runs again when dep changes to [2]. Skips the final identical [2].

Key Insight: useEffect compares deps shallowly by reference. Same values in a new array still triggers the effect if references differ — this is why objects/arrays as deps cause infinite loops.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz