Bootcamp
Search…
8.3.2: useReducer

Introduction

useReducer is an alternative to useState that allows us to provide a function (called a "reducer") that manipulates state in a pre-defined way. useReducer and the reducer function allow us to manipulate state in more complex ways. The reducer function is a helper function for state manipulation, and allows us to set new state based on the value of the previous state.

Example

The following example comes from the official React useReducer documentation here.
We can call our reducer function via the dispatch method returned by useReducer, which wraps our reducer function and passes the relevant parameters to it. The 1st parameter passed to dispatch is the 2nd parameter passed to reducer, i.e. the action JS Object parameter.
const initialState = {count: 0};
​
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
​
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}

What's Next

We'll combine useReducer with useContext's Provider higher-order component to create a global-state-setting function that is available without lifting functions.

Additional Resources

  1. 1.
    Web Dev Simplified provides a video explanation of useReducer​