Normally, you would use useState
to store values in your function components. However, when your state value is a complex data object or is comprised of a number of related values, you may want to use useReducer
instead. This hook allows you to avoid having numerous state hooks and, instead, consolidate your values.
Like useState
, the array returned by the hook contains two values: your current state and a dispatch function which allows you to update the state. When instantiating the hook, you'll need to pass it two arguments, a reducer function and your initial state. Similar to patterns used in libraries like Redux, when you dispatch an action the reducer function body will determine how to update the internal state.
This is the function signature of the useReducer
hook:
const [state, dispatch] = useReducer(reducer, initialState)