Extracting State Logic into a Reducer
- What is the motivation for adding a reducer?
A reducer can simplify complex state logic that involves multiple sub-values, or when the next state depends on the previous one. It also helps in testing and isolates the state logic from the components.
- What are actions in the context of a reducer? How are they different than setting state directly?
Actions in a reducer are plain objects that represent an action to be performed on the state, and usually have a 'type' property. They are different from setting state directly because they describe the changes in an abstract way, without mutating the state directly.
- What common list operation is useReduce named for, and why?
useReduce is named after the reduce function in JavaScript, which is used to apply a function against an accumulator and each element in the array (from left to right) to reduce it to a single output value.
- When should you switch from useState to useReducer?
The switch from useState to useReducer should be done when you have complex state logic that involves multiple sub-values, or when the next state depends on the previous one.
Keep these pages handy - they answer questions that show up regularly for this lab.
- check out Josh's code
- Google Bard and ChatGPT