React Hooks useContext and useReducer 3 — Questions and Answers
Question 1: Which hook do you use inside a component to read a context value?
- useContextValue
- useContext (Correct answer)
- useProvider
- useConsumer
Correct answer: useContext
The useContext hook is the built-in React hook for reading a context value inside a function component.
Question 2: How do you update context value from a child component?
- Mutate the context object directly
- Provide a setter or dispatch function as part of the context value (Correct answer)
- Call createContext again
- Use useRef
Correct answer: Provide a setter or dispatch function as part of the context value
Including an updater function (setState or dispatch) in the context value allows consumers to trigger changes.
Question 3: What performance optimization prevents context consumers from re-rendering when unrelated state changes in the Provider?
- Using React.memo on the Provider
- Memoizing the context value with useMemo (Correct answer)
- Calling useContext conditionally
- Splitting into multiple contexts
Correct answer: Memoizing the context value with useMemo
Wrapping the context value in useMemo ensures the same reference is passed unless the actual data changes.
Question 4: What is the immer library often used for with useReducer?
- Async reducers
- Writing reducers with mutable syntax that produce immutable state (Correct answer)
- Serializing actions to localStorage
- Debugging dispatches
Correct answer: Writing reducers with mutable syntax that produce immutable state
Immer lets you write reducer logic as if you are mutating state, while actually producing a new immutable state.
Question 5: Can you call dispatch from inside a useEffect?
- No, dispatch is not available inside effects
- Yes, and dispatch is stable so it won't need to be in the dependency array (Correct answer)
- Yes, but it must be listed in the dependency array
- Only in the cleanup function
Correct answer: Yes, and dispatch is stable so it won't need to be in the dependency array
React guarantees dispatch identity is stable across renders, so it does not need to be listed as a dependency.
Question 6: How should you pass context to a deeply nested child?
- Prop drill through every component
- Wrap ancestor components in the Context Provider and consume with useContext (Correct answer)
- Use a global window variable
- Use component refs
Correct answer: Wrap ancestor components in the Context Provider and consume with useContext
Wrapping the ancestor with a Provider and calling useContext in the descendant eliminates prop drilling.
Which hook do you use inside a component to read a context value?