I have a below redux state
state:{
prop1:
prop2:
prop3:
}
Each property value comes from a dropdown element on the UI.
What would be the best way to update the state when onChange
of any of these inputs. Update the whole object when any of these inputs change or write a separate case statement in reducer to update each prop individually? Any thoughts or suggestions would be helpful.
You can dispatch action with type of action and payload as input field name and value and then change that particular field only. And then you can Reselect that particlar property only which will further memoize value for that field, thus no-render of component when other props change happens.
So my approach would be.
dispatch({
type: 'UPDATE_PROFILE_FIELD',
payload: {
'field_name': 'first_name',
'value': 'John Doe',
}
});
Then on reducer:
switch (action.type) {
case 'UPDATE_PROFILE_FIELD':
const { field_name, value } = action.payload;
// field_name can be first_name, last_name, phone_number
const newState = Object.assign(oldState, { [field_name]: value });
...
...
// Update new state as desired
return newState;
}
Then using Reselect, we can select only that field from particular state.
const profileSelector = (state) => state.profile
const getFirstName = (profileSelector, profile) => profile.first_name
Now, we can use getFirstName()
in our components.
Also, I reocmmend using immutable state (see Immerjs), changing original object will lead to mutation issues that can lead to other issues like unnecessary re-render, un-synced react states etc.