React Hooks useContext and useReducer 2 — Questions and Answers
Question 1: What is the third argument to useReducer used for?
- Setting the dispatch function
- Lazy initialization of state via an init function (Correct answer)
- Providing the context value
- Setting the reducer type
Correct answer: Lazy initialization of state via an init function
The optional third argument is an init function called with the second argument to lazily initialize state.
Question 2: How does React compare Provider values to decide if consumers re-render?
- Deep equality check
- Object.is (reference equality) (Correct answer)
- JSON.stringify comparison
- Component-level shouldUpdate
Correct answer: Object.is (reference equality)
React uses Object.is to compare old and new context values, so new object literals always trigger re-renders.
Question 3: Which pattern combines useContext and useReducer to mimic a Redux-like store?
- Passing dispatch through props
- Storing state and dispatch in a context Provider (Correct answer)
- Using useRef to share state
- Using localStorage
Correct answer: Storing state and dispatch in a context Provider
Placing useReducer's state and dispatch into Context lets any descendant read and update shared state without prop drilling.
Question 4: What happens if no Provider wraps a component that calls useContext?
- React throws an error
- The hook returns the default value passed to createContext (Correct answer)
- The hook returns undefined always
- The component is skipped
Correct answer: The hook returns the default value passed to createContext
If no Provider is found, useContext returns the default value specified when the context was created.
Question 5: In a useReducer action, what property typically identifies the type of state change?
- action.id
- action.type (Correct answer)
- action.name
- action.payload
Correct answer: action.type
By convention, actions have a type string that the reducer uses to determine which state transition to perform.
Question 6: How do you pass additional data along with a useReducer action?
- Add it to the action.type string
- Include a payload property in the action object (Correct answer)
- Pass it as a third argument to dispatch
- Use a separate useState
Correct answer: Include a payload property in the action object
A payload property on the action object carries the data needed by the reducer to update state.
What is the third argument to useReducer used for?