2

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.

Samundra
  • 1,869
  • 17
  • 28
dev0864
  • 465
  • 2
  • 7
  • 17

2 Answers2

2

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.

Samundra
  • 1,869
  • 17
  • 28
1

In my own opinion,

From the performance view, I think it is more efficient to update the whole Object. From the bum's law (LOL), it is also better to update the whole Object, you need less code In your reducer.

Note: Unless you need a little more complex logic, I think it is Ok update the whole object.

If you're using any of these Object keys as a prop or in the state logic in other components you need to take in mind that this could trigger some re-renders.

Yoandry Collazo
  • 1,122
  • 9
  • 16