Fullstack CourseLearn by building
Back to week 4

Topic

Challenge: stale state and Effects

Definition

A stale closure occurs when asynchronous or deferred code reads state captured by an earlier render instead of the current value required by the behavior.

In simpler words

A timer or Effect can remember an old value if its dependencies or update form are wrong.

This challenge reinforces that Effects synchronize external systems; they are not a workaround for state flow.

After this you can

  • Spot a stale state bug
  • Select a dependency-safe update

Debug the render boundary

Definition

React closures capture values from the render that created them, so state updates based on a previous value should use the functional updater form.

In simpler words

Let React supply the latest value instead of trusting an old captured value.

Inspect the Effect dependencies and whether the callback needs the previous state.

Keep cleanup paired with subscriptions and timers.

Challenge lab

Bug report

The elapsed counter sometimes stops at 1 after a route transition.

What is broken

An interval Effect calls setElapsed(elapsed + 1) with an empty dependency list.

Broken snippet

useEffect(() => {
  const id = setInterval(() => {
    setElapsed(elapsed + 1); // stale closure
  }, 1000);
  return () => clearInterval(id);
}, []); // elapsed missing — and restarting on elapsed is worse

Pass criteria

  • Counter continues from the current value
  • Interval is cleaned up on unmount
  • No unnecessary Effect restart

Choose the correct fix

Keep in mind

  • If a value is derived during render, do not mirror it into Effect-managed state.

Test

Check your understanding

At least 10 questions — mix of concept, syntax, practical, and logic. Score ≥ 80% (enforced by the API) to save progress.

Checking your session…

10 questions · concept 3 · syntax 2 · practical 3 · logic 2

Concept1. Which statement is the most accurate definition of the stale state challenge?
Syntax2. Which code-level choice is consistent with the stale state challenge?
Practical3. A reviewer sees this situation. Which decision best applies the stale state challenge?
Logic4. What reasoning correctly explains why this approach works for the stale state challenge?
Concept5. Which boundary does the correct use of the stale state challenge preserve?
Practical6. What is the safest next step when implementing the stale state challenge?
Syntax7. Which implementation direction matches the rule for the stale state challenge?
Logic8. Which consequence follows from applying the stale state challenge correctly?
Concept9. Which claim about the stale state challenge is true in this monorepo?
Practical10. Which team practice best demonstrates the stale state challenge?