reactintermediate
React State Management
useState, useReducer and Context
7 questions
By EZ4Code Team
1. What is the structure of the return value of useState?
An array [state, setState]
An object {state, setState}
Only state
Only setState
Explanation: useState returns a two-element array [current state, setter function], typically named using array destructuring.
2. What is the problem with the following code? setCount(count + 1) setCount(count + 1)
setCount(count + 1)
setCount(count + 1)Both are based on the same count in the closure, only increments by 1
Increments by 2
Error
No effect
Explanation: React state updates may be batched asynchronously; consecutive setCount(count+1) are based on the same closure count; use functional update setCount(c => c + 1).
3. What is the advantage of useReducer over useState?
Suitable for managing complex/related multi-field state, centralized via action
Always better performance
Does not need an initial value
Only for global state
Explanation: useReducer extracts state logic into a reducer, suitable for complex state transitions and multiple related sub-values, easier to test and maintain.
4. What does useContext do?
Consumes Context across component levels, avoiding prop drilling
Creates state
Replaces useState
Handles side effects
Explanation: useContext reads the value provided by the nearest Context.Provider, enabling cross-level data passing and avoiding prop drilling.
5. What is the main performance issue with Context?
When the Provider value changes, all components consuming that Context re-render
Cannot pass functions
Only for class components
Does not support nesting
Explanation: Context value changes cause all consuming components to re-render, potentially causing performance issues; split Context or use memo/state libraries to optimize.
6. What is lifting state up?
Putting shared state into the nearest common parent component
Putting state globally
Deleting state
Using Context instead
Explanation: When multiple child components need to share the same state, lift it to the common parent and pass down via props; this is one of React's recommended sharing approaches.
7. Which scenario is suitable for useState rather than useReducer?
Independent, simple state (such as toggle, counter)
Multiple interdependent fields
Complex state machines
Needs global sharing
Explanation: Simple independent state is more concise with useState; complex related state or transitions based on previous state are clearer with useReducer.