so in react hooks we may have multiple states in our component:
const [stateA, setStateA] = useState(0);
const [stateB, setStateB] = useState('Hello World');
const [stateC, setStateC] = useState(true);
but there is a case that we need to update multiple states at once. let say when clicking event:
const handleClick = () => {
setStateA(prev => prev+1);
setStateB('John Doe');
setStateC(false);
}
As we can see I need to update these states 1 by 1. So to update all states at once and ensure all updates in the same batch, I tried making this reducer:
const stateReducer => (prev, next) {
switch (typeof next) {
case 'object':
return { ...prev, ...next };
case 'function':
return { ...prev, ...next(prev) };
default:
return prev;
}
...
const [state, setState] = useReducer(stateReducer, {
stateA: 0,
stateB: 'Hello World',
stateC: true
});
...
// just set single state
setState({stateA: 0});
// set multiple state
setState({
stateA: 5,
stateB: 'John Doe'
});
// set multiple state with prev state
setState(prev => ({
stateA: prev.stateA +1,
stateB: 'John Doe',
stateC: !prev.stateC,
}));
It's works! but how it gonna affect the performace? or this is okay?
Your performance will not be affected.
In the note section of the page Functional updates in the react hooks reference they post useReducer as an alternative for useState when we need to manage different state variables.
Another option is useReducer, which is more suited for managing state objects that contain multiple sub-values.
The performance key does not reside in the usage of useState or useReducer itself, it's more about why do you need to use it, and as they say in the useReducer documentation you are doing a good usage of it simplifying the way you handle this 3 state variables.
useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.
Not 100% sure about this but I think useState use useReducer internally.