useReducer hook
- The
useReducer hook is an alternative to useState that’s ideal for complex state logic, multiple related state values, or predictable state transitions
- useState hook limitations → complex state logic with multiple sub values, when next state depends on previous state
- useState → initial state vs. useReducer → initial state + reducer function
useReducer manages state using:
- A state object
- A reducer function (how state changes)
- actions that describe what happened
- const [state, dispatch] = useReducer(reducer, initialState);
state → current state
dispatch → sends actions
reducer → pure function that returns new state
useReducer example
ex. track cost of ingredients + income from selling meals
- displays wallet with initial value 100
- wallet reduces by 10 when shopping for veggies
- wallet increases by 10 when serving a meal

useReducer vs. useState
- useState → primitive data types: strings, numbers, booleans
- useReducer → complex data: arrays, objects
- One negative characteristic of useState is that it often gets hard to maintain as the state gets more complex.
- One negative characteristic of useReducer is that it requires more prep work to begin with. There's more setup involved. However, once this setup is completed, it gets easier to extend the code based on new requirements
additional resources
- The useReducer hook reference in the React docs discusses the basics of useReducer, along with specifying initial state and lazy initialization.