Quiz · Hard
Applied questions on useEffect dependencies and cleanup, race conditions, stale closures, refs, memo and useCallback, context re-renders and React 19 hooks.
Which situation is the correct use of useEffect?
Handling a button click
Resetting a form's fields when the user prop changes
Computing fullName from firstName and lastName
Opening a WebSocket connection and closing it in the cleanup
Effects synchronize with external systems. fullName can be computed during render, clicks belong in event handlers, and resetting state on a prop change is done with a key.
What is the main difference between useMemo and useCallback?
useCallback runs after render; useMemo before
useMemo caches a computed value; useCallback caches a function (it is useMemo(() => fn, deps))
They are identical and interchangeable names
useMemo is for async work; useCallback is synchronous
useCallback(fn, deps) returns the same function identity until deps change, useful for stable props or dependencies. useMemo returns whatever its factory returns. Neither guarantees the cache is kept forever.
What is logged by the effect's callback after the first click, and why?
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => console.log(count), 1000);
return () => clearInterval(id);
}, []);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}It keeps logging 0: the interval callback closed over count from the first render (stale closure)
It logs 1, then 2, then 3
It throws because count is not in the dependency array
It logs the latest count each second
The [] array means the effect (and its closure over count = 0) is created once. Fix by adding count to the dependencies (restarting the interval each change) or by reading the latest value through a ref.
What does this component do when mounted, and why?
const [n, setN] = useState(0);
useEffect(() => {
setN(n + 1);
});It increments n once for every click
It increments n once
It never runs the effect
It re-renders in an endless loop, because the effect has no dependency array and sets state every time
With no dependency array the effect runs after every render. Setting state triggers a render, which runs the effect again, forever (React will eventually warn about too many updates).
useEffect(() => { fetchUser(id).then(setUser); }, [id]); can show the wrong user when id changes quickly. What is the problem and the standard fix?
The effect must run only once with []
Promises cannot call setUser
useEffect cannot depend on id
A race condition: an old request can finish last. Ignore or abort outdated requests in the cleanup
Responses may arrive out of order. In the cleanup set a flag (let ignore = true) or abort the request, so only the latest request's result is stored. Query libraries do this for you.
What is the order of logs when a component mounts, then its id prop changes?
useEffect(() => {
console.log('effect', id);
return () => console.log('cleanup', id);
}, [id]);(id starts at 1 and becomes 2; ignore StrictMode.)
effect 1, effect 2
effect 1, cleanup 2, effect 2
effect 1, effect 2, cleanup 1
effect 1, cleanup 1, effect 2
Before running the new effect, React runs the previous effect's cleanup with the values from that earlier render (id 1). Then the new effect runs with id 2. On unmount only cleanup runs.
A parent renders <Child onSave={() => save()} /> where Child is wrapped in React.memo. The child still re-renders every time the parent does. Why?
The child must also call useMemo
React.memo does not work with function props
The inline arrow function is a new function on each render, so the prop is never shallowly equal
React.memo only works with class components
React.memo compares props with Object.is. A new function identity each render means the props differ. Stabilize it with useCallback (or let the React Compiler do it) or avoid passing it.
What does useRef give you, compared with useState?
A global store shared between components
A mutable .current value that persists across renders without triggering a re-render when it changes
A value that resets on every render
A value that triggers a re-render when changed
Refs hold values you need to remember but not display (timer ids, DOM nodes, previous values). Changing ref.current does not notify React.
Which code correctly focuses an input when the component first mounts?
const [el, setEl] = useState();
el.focus();
return <input />;const ref = useRef(null);
ref.current.focus();
return <input ref={ref} />;const ref = useRef(null);
useEffect(() => { ref.current.focus(); }, []);
return <input ref={ref} />;return <input autoFocus={useEffect()} />;The ref is only attached to the DOM node after the commit, so .focus() must be called in an effect (or a ref callback). During render ref.current is still null, which would throw.
Why does useContext(ThemeContext) re-render every consumer when the provider's value is a new object each time?
<ThemeContext.Provider value={{ mode, toggle }}>Consumers always re-render regardless of the value
Context compares the value by reference; a new object on each render is a change, so all consumers update
useContext cannot read objects
React deep-compares the value and finds a difference
If the provider's parent re-renders, { mode, toggle } is a new object, so consumers re-render even if mode is unchanged. Memoize the value with useMemo or hold it in state.
In React 19 a function component should receive a ref how?
Only through forwardRef
Refs cannot be passed to function components
Through useRef inside the child
As a regular prop: function Input({ ref, ...rest }) { ... }
React 19 made ref an ordinary prop for function components, so forwardRef is no longer required (it keeps working for backwards compatibility).
Which hook lets a component show the result of an async action immediately, then settle to the real result?
useLayoutEffect
useId
useMemo
useOptimistic
useOptimistic(state, updater) returns an optimistic value while a transition or action is pending (for example a new comment shown right away), and reverts or confirms when the real state arrives.
What does useLayoutEffect do differently from useEffect?
It runs after the browser has painted, like useEffect
It runs synchronously after DOM changes but before the browser paints, so you can measure and adjust layout without flicker
It runs only on the server
It runs before the component renders
Because it blocks painting, use it only when you need to read layout and synchronously re-render. Prefer useEffect for everything else.
A component calls useState conditionally:
if (user) {
const [theme, setTheme] = useState('light');
}What is the problem?
useState cannot take a string
Nothing; React supports conditional hooks
theme is not defined outside the if
Hooks must be called in the same order on every render; the condition can shift later hooks to wrong state slots
React identifies hooks by call order. A conditional hook changes the order between renders and corrupts state (React throws an error about a changed number of hooks). Call it unconditionally and use the condition in the logic.
In which order do useEffect callbacks run on the first mount of a parent and its child?
Child effect first, then the parent effect
Only the parent's effect runs
Both at once in random order
Parent effect first, then the child
Effects run after the commit, from the leaves upward. Rendering itself goes parent to child, but effects fire child before parent.
When is a useReducer a better fit than several useState calls?
When you need to avoid re-renders entirely
When updates involve several related fields or complex transitions, so a pure reducer centralizes the logic
When you want state to survive page reloads
When state is a single boolean
A reducer turns updates into named actions and keeps the transition logic in one testable pure function. A single boolean is simpler with useState, and neither hook persists data on reload or avoids renders.
What does the React Compiler change for your code?
It converts class components to function components
It removes the need for keys
It makes components render on the server
It automatically adds memoization at build time, reducing the need for manual useMemo, useCallback and memo
The compiler relies on the Rules of React (pure render, immutable updates) and inserts caching where it is safe. It does not change semantics, add server rendering or replace keys.