Today I learned about the useReducer React Hook, which helps us in managing the state for our component and it is similar to the useState hook, but useReducer becomes really helpful when we want to separate the state logic from the component that is trying to manage the state.
useReducer also comes in handy when we have a single state object that is getting used and mutated in multiple components.
So basically, when we want to maintain a user profile using useState, we will use the following syntax:
const [profile, setProfile] = useState({
name: 'Sourabh Bagrecha',
medium: 'medium.com/@sourabhbagrecha',
github: 'github.com/sourabhbagrecha',
linkedin: 'linkedin.com/in/sourabhbagrecha'
});
Whenever we want to make changes to the profile, we can simply do that in the following manner:
setProfile({...profile, name: "SOURABH BAGRECHA"})
But this approach is prone to bugs and can cause errors if the state is not handled in a standard way throughout different children components.
To overcome this, we can use the useReducer Hook, there are multiple ways to tackle this using useReducer, one of them is using it in the following manner:
const initialState = {
name: 'Sourabh Bagrecha',
medium: 'medium.com/@sourabhbagrecha',
github: 'github.com/sourabhbagrecha',
linkedin: 'linkedin.com/in/sourabhbagrecha'
}
const profileReducer = (state, action) => {
return {...state, ...action}
};
const [profile, setProfile] = useReducer(profileReducer, initialState);
The useReducer setup is a little bit more complex than the useState setup, but now, updating the profile state has become very seamless:
setProfile({name: "SOURABH BAGRECHA"})
As we can see, we don’t have to worry about the state of the rest of the profile object. All we did above is updated the name property and our profile-reducer will take care of everything.