React Hooks: useReducer

While updating my React project to use hooks, I used a few of the more essential hooks. From React, I used useState to manage state and useEffect to handle side effects, and from Redux I used useDispatch to dispatch to my redux store and useSelector to select the portion of the redux store that I want to use in a specific component. One hook that I had decided to stay away from in that initial update was the useReducer hook, which is an alternative to useState that can be used to manage larger or more complex state.

Too Many useStates!

This is what my component’s state looked like before updating to useReducer. Since I had to use multiple useState hooks in my form, I was repeating myself quite a bit here! I was able to use useReducer to dry up my code, removing the first 5 lines of state.

useReducer

This is the basic structure of useReducer, which takes two arguments. The formReducer, which will be used to dispatch any updates to the formState, and the initialState, which is somewhat self-explanatory (it’s the value that each aspect of state begins with).

initialState
formReducer

The reducer will generally be a switch statement. In my case, it’s a simple switch with a case designed to handle any change in the form’s input fields. The reducer will then spread apart state, determine which passed-in field is being altered, and change that aspect of state to be the current value of the field. This logic is dispatched inside a function that’s passed on change with each of the form’s input fields.

handleTextChange function for the Form Fields

In this dispatch call inside handleTextChange, the action type is determined by the case used in the reducer, the field is determined by the name given to each input field, and the payload is determined by what is being filled out in each input field.

Completed Form With handleTextChange for useReducer

There you have it! This is a pretty basic way to utilize the useReducer hook in React. Since useReducer is meant to be used in place of useState in situations where the state is larger or more complex than normal, any decently-sized form component is the perfect place to use it instead of useState!