In my previous blog, I gave a basic demonstration on how to manage state with useReducer
instead of useState
. In this blog, I'll dive into a more complex example.
When managing state for a form, things can get complex quickly. Take this form, for example:
To manage the form's state locally with useState
, it would look something like this:
const [name, setName] = useState('')
const [title, setTitle] = useState('')
const [favoriteNumber, setFavoriteNumber] = useState('')
const [favoriteColor, setFavoriteColor] = useState('')
This might seem manageable enough for now - but if the form needs to grow, one useState
per input will turn your code into spaghetti before you know it! Let's take a look at how we can make state management more scaleable with useReducer
using the same steps shown in my previous blog:
Define an initial state and an action type.
Replace the
useState
hook with theuseReducer
hook.Create a reducer function that takes a state and an action and returns a new state.
Update the component to use the new state and dispatch functions returned by the
useReducer
hook, which should have the reducer and initial state passed in.
Following the steps above, we can convert our useState
state to useReducer
state.
1. Define an initial state and an action type:
const initialState = {
name: 'Default name',
title: 'Default title',
favorite_number: '3',
favorite_primary_color: 'red',
};
const INPUT_CHANGE = 'inputChange';
2. Replace the useState
hook with the useReducer
hook:
import { useReducer } from 'react';
const FormComponent = () => {
const [formData, setFormData] = useReducer(formReducer, initialState);
// ...
}
3. Create a reducer function that takes a state and an action and returns a new state:
const formReducer = (state, action) => {
const stateCopy = { ...(state || {}) };
switch(action.type) {
case INPUT_CHANGE:
return {
...stateCopy,
[action.payload.name]: action.payload.value
}
default:
return null;
}
}
4. Update the component to use the new state and dispatch functions returned by the useReducer
hook, which should have the reducer and initial state passed in:
const FormComponent = () => {
const [formData, setFormData] = useReducer(formReducer, initialState);
const internalOnchange = (type, payload) => {
setFormData({ type, payload })
};
// ...
return (
<form>
<input
type="text"
id="name"
name="name"
onChange={event => {
internalOnchange(INPUT_CHANGE, {
name: event.target.name,
value: event.target.value,
});
}}
/>
{/* ... */}
</form>
);
}
Step 4 is a little more complex in this example. In order to pass the type and payload to the reducer cleanly, I've implemented an internalOnchange
helper function. Now the internalOnchange
can be passed into any input on the form, as shown on the name input above.
As long as the name attribute of the input matches the data you want to change, that value in state will be changed. Now the form can have unlimited inputs with no need to change the state management functionality!
...unless the form gets even more complex?? Not a problem, you can add another action to your formReducer
to manage any specialized inputs. To see this form as a completed project, check it out here on Github.
I've created the example form explained above - it changes state independently by action, but I've also included an option to change the data as a whole by manipulating the entire JSON directly. This is done by passing the entire changed JSON as the payload here and using an updateData
action, created here. This project will look a little different than the blog example since it's done in TypeScript, I wanted to keep things simple in this blog so I explained it in JavaScript.
I hope this blog clearly explained using useReducer
to handle state instead of useState
. If you have any questions or comments, I'd love to hear what you've got!