Q1. What is the useReducer hook?
useReducer is a React hook for managing complex state logic. It accepts a reducer function and an initial state, and returns the current state and a dispatch function. It's similar to Redux's reducer pattern and is often used when state transitions are complex or depend on previous state.
Q2. How do you use useReducer?
Define a reducer function: (state, action) => newState. Then call const [state, dispatch] = useReducer(reducer, initialState). Call dispatch with an action object (e.g., { type: 'INCREMENT' }) to update state.
Q3. When would you use useReducer over useState?
Use useReducer when state logic is complex, involves multiple sub-values, or when the next state depends on the previous one in a non-trivial way. It also makes state transitions more predictable and testable.
Q4. What is an action in useReducer?
An action is an object that describes what happened. It usually has a type property and optionally a payload. The reducer uses the type to determine how to update the state.
Q5. Can you use useReducer with useContext?
Yes, combining useReducer with useContext is a common pattern for global state management. You can pass the state and dispatch down via context, allowing any child to read state and dispatch actions without prop drilling.
