Stale Closures and Update Timing — Concept Check
Questions on Stale Closures and Update Timing. A callback captures the state from the render that created it. When that callback outlives the render — a timer, a listener, a subscription — it keeps reading values that are no longer current.
Questions in this quiz
7 questions on Stale Closures and Update Timing — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.You have a React component with a timer that updates a counter. After the first update, the counter stops incrementing. What is likely causing this issue?
- AThe useEffect dependency array is incorrect.
- BThe component is unmounted after the first render.
- CThe closure captures the initial state, causing a stale closure.
- DThe setInterval function is not running.
2.In a React component, you want to ensure a WebSocket handler always uses the latest filter value without re-subscribing. What approach should you use?
- AStore the filter in a ref and update it in a useEffect.
- BUse a functional updater for the filter state.
- CRecreate the WebSocket connection on every filter change.
- DUse a dependency array with the filter in useEffect.
3.A developer notices that a counter in their React app is stuck at 1. They used setInterval in a useEffect with an empty dependency array. What should they do to fix it?
- AAdd count to the dependency array.
- BUse componentDidMount instead of useEffect.
- CRemove the useEffect entirely.
- DUse a functional updater in setCount.
4.When reading state immediately after setting it in React, the console logs the previous state value. Why does this happen?
- AThe state update is batched and delayed.
- BThe component is not re-rendering properly.
- CState updates are asynchronous and don't reflect immediately.
- DThe console.log is placed before the state update.
5.A developer uses useEffect with an empty dependency array to manage a WebSocket connection. They want to ensure the connection uses the latest data without re-subscribing. What should they do?
- ARecreate the connection on every data change.
- BUse flushSync to force updates.
- CUse a ref to store the latest data.
- DAdd all data dependencies to the array.
6.A React developer wants to perform an action right after setting a state value. Which method should they avoid relying on?
- APassing the new value directly to a function.
- BUsing the state value immediately after setting it.
- CReacting to the state change in a useEffect.
- DUsing the functional updater pattern.
7.A developer uses useEffect to update a counter and notices it resets on every render. What is a likely cause?
- AThe component is not using useState correctly.
- BThe counter is not initialized properly.
- CThe effect depends on the counter state, causing re-renders.
- DThe useEffect is missing a dependency array.