React REACT 2 β Questions and Answers
Question 1: What does the useEffect cleanup function run before?
- Before the next effect re-runs and on unmount (Correct answer)
- Only on initial mount
- After every render unconditionally
- Only when state is reset
Correct answer: Before the next effect re-runs and on unmount
The cleanup function runs before the effect executes again and when the component unmounts.
Question 2: Which hook should you use to memoize an expensive computed value?
- useMemo (Correct answer)
- useCallback
- useRef
- useReducer
Correct answer: useMemo
useMemo caches a computed value and recomputes only when dependencies change.
Question 3: What is the purpose of the key prop when rendering a list?
- Help React identify which items changed, added, or removed (Correct answer)
- Style each list item uniquely
- Set the order numerically
- Bind event handlers automatically
Correct answer: Help React identify which items changed, added, or removed
Keys give elements a stable identity so React can efficiently reconcile list changes.
Question 4: Why is using an array index as a key often discouraged?
- It can cause incorrect state when the list reorders (Correct answer)
- It is slower to compute
- React forbids numeric keys
- It breaks TypeScript typing
Correct answer: It can cause incorrect state when the list reorders
Index keys can mismatch component state when items are inserted, deleted, or reordered.
Question 5: What does useCallback return?
- A memoized version of the callback function (Correct answer)
- A cached computed value
- A ref object
- A new component instance
Correct answer: A memoized version of the callback function
useCallback returns a memoized callback that changes only when its dependencies change.
Question 6: In React, what is a controlled component?
- A form input whose value is driven by React state (Correct answer)
- A component wrapped in memo
- A class component with refs
- A component rendered by a portal
Correct answer: A form input whose value is driven by React state
A controlled component's value is controlled by React state via value and onChange.
Question 7: What hook lets you access a DOM node directly?
- useRef (Correct answer)
- useState
- useContext
- useMemo
Correct answer: useRef
useRef creates a mutable ref that can be attached to a DOM element via the ref attribute.
What does the useEffect cleanup function run before?