QuizNot attempted
Spot the bug: stale closures in the observer
1–4 to choose, Enter to submit
Show answer & explanation
Correct answers:
- It only works by accident: isFetching flips after every load, which happens to re-create the observer with a fresh loadMoreData
- If a new filter returns a different data array of the same length, the observer can keep slicing the old array
- The setTimeout callback writes displayData from the render that scheduled it, overwriting anything that changed during that second
- A closure sees the values of the render that created it.
- The deps don't list what the callback reads, so correctness depends on
isFetchingtoggling. - Robust fixes: functional updates (
setRows(prev => [...prev, ...next]),setPage(p => p + 1)), or a reducer so the observer only dispatchesloadMoreand the reducer decides with current state. useEffectEvent(stable in React 19.2) also gives an effect a non-reactive callback that reads the latest values.react-hooks/exhaustive-depsflags the missing deps.- Not effects read the latest values: each effect run captures one render's values
- that is the whole stale-closure problem.