Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 06 / Topic 4 of 7

The dependency array's real job: when effects rerun

The dependency array is not a performance knob - it exists to answer one question correctly: when does this effect's closure need to be rebuilt? examples/03_dependency_array_missing_deps.jsx's DeliveryRadiusWatcherBroken listens for a delivery-partner location ping and checks it against a configurable radius, but leaves that radius out of the array:

// examples/03_dependency_array_missing_deps.jsx (broken)
export function DeliveryRadiusWatcherBroken({ radiusKm }) {
  const [verdict, setVerdict] = useState("waiting for a location ping");
  // ...
  useEffect(() => {
    function handlePing(event) {
      const { distanceKm } = event.detail;
      setVerdict(distanceKm <= radiusKm ? "within radius" : "outside radius");
    }
    window.addEventListener("location-ping", handlePing);
    return () => window.removeEventListener("location-ping", handlePing);
  }, []); // BUG: handlePing reads radiusKm, but radiusKm is missing here
  // ...
}

handlePing is a closure created the first time this effect runs, and it captured whatever radiusKm was at that exact moment - 3, say. Because the dependency array is [], the effect never reruns, so that closure - and the stale 3 trapped inside it - is the only listener this component will ever have, no matter how many times a new radiusKm prop arrives afterward. Mounting the broken version with radiusKm={3}, rerendering with radiusKm={1}, then dispatching a ping at 2km really still reports "within radius", checked against the original 3 (examples/03_dependency_array_missing_deps.test.jsx) - the tightened radius is silently ignored. DeliveryRadiusWatcherFixed is identical except for }, [radiusKm]) - the only change needed. The same prop change on the fixed version really reports "outside radius", checked against the current 1.

Done here? The practice set for Part 6 — including the solutions — is on the part page.

Search the guide