React Hook with Reducer Pattern

Learn how the “useReducer” hook helps manage state with React Hooks. The lesson will also cover use cases and example usage.

What is it?

useReducer hook is an alternative to useState. It offers more control on the next state value based on a given action.

If you are familiar with Redux Reducers, useReducer hook provides similar functionality out of the box in React.

When do we use it?

useReducer can be used in the following scenarios:

  • The shape of state object is complex. Maintain multiple items within the same state object.
  • Access previous state value to update the next state.
  • Apply special logic on certain actions to calculate the next state.

Note that some of these points can be achieved by using useState hook. However, it would require maintaining more code in the shape of various functions. In the upcoming section, Managing Global State with Hooks, the benefits of the useReducer hook and how it can help maintain large state objects in a cleaner way is explained in detail.

Syntax

The useReducer hook accepts three arguments:

  • Reducer: This is the reducer function. When an action is dispatched, it is called with the current state and the action as first and second argument respectively.
  • Initial State: Supply the value of the initial state here.
  • Init Callback: This parameter is optional. You should only supply it when looking to initialize a state which is based on a custom value or prop at a later stage. When provided, React will call this function as initCb(initialState) to obtain the initial state for the useReducer hook.
const [state, dispatch] = useReducer(reducer, initialState, initCb);

It returns an array with state value and dispatch function.

The dispatch function is similar to the setState function seen in useState hook. However, it is a special use case function. When dispatch is called, React will automatically call the reducer with the action provided to the dispatch function.

By using

dispatch({ type: 'REFRESH', message: 'hello' })

It will result in this:

reducer(state, { type: 'REFRESH', message: 'hello' })

Get hands-on with 1200+ tech skills courses.