useEffect.dev
← Back to lessons

Lesson 11. Simplify state update logic with reducers 5. Exercise & next steps

While the logic of useReducer might seem complicated, it’s a hook that you can rewrite with only a few lines of code. Are you able to write your custom implementation of it?

Result
Click here to see the solution!

The custom hook uses useState to store the reducer’s state. To update it, it returns a dispatch function. This functions:

  • computes the new state using the action and the reducer: reducer(state, action)),
  • updates the state using setState.
const useMyReducer = (reducer, initialState) => {
const [state, setState] = useState(initialState)
const dispatch = (action) => setState(reducer(state, action))
return [state, dispatch]
}

Next steps

In the next lesson, we’ll see some example of custom hooks to use the APIs provided by the browser.