Skip to content

QuizNot attempted

Spot the bug: stale closures in the observer

The observer callback calls loadMoreData, which reads currentPage, displayData and data, but the effect only lists [isFetching, totalItems]. Which statements are true?
const loadMoreData = () => {
if (currentPage < totalItems && !isFetching) {
setIsFetching(true);
setTimeout(() => {
const start = currentPage * itemsPerPage;
setDisplayData([...displayData, ...data.slice(start, start + itemsPerPage)]);
setCurrentPage(currentPage + 1);
setIsFetching(false);
}, 1000);
}
};
useEffect(() => {
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) loadMoreData();
});
if (lastElementRef.current) observer.observe(lastElementRef.current);
return () => observer.disconnect();
}, [isFetching, totalItems]);

Select all that apply.

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 isFetching toggling.
  • Robust fixes: functional updates (setRows(prev => [...prev, ...next]), setPage(p => p + 1)), or a reducer so the observer only dispatches loadMore and 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-deps flags the missing deps.
  • Not effects read the latest values: each effect run captures one render's values
  • that is the whole stale-closure problem.