I have example from React
where component update depends on does the props
will be object or array type. Using reselect
library and Redux store
. Does it suppose to be like that, meaning the new object willn't be equal to prevprops
? And if it is suppose to work this way, how can I work with the objects and new props in redux
so shouldComponentUpdate
will work for me when changes with object occur in props
?
Asked
Active
Viewed 78 times
0

Zak the Gear
- 131
- 2
- 14
-
Why would you need to use shouldComponentUpdate manually? Redux automatically instructs the react to re-render if a new state was returned from reducer. I am confused of the question tbh. – Sudhanshu Kumar Sep 18 '20 at 13:40
-
Hello Ashu, did you opened the example? There is no automatically re-render if you will use object there as props. You can see it in console. So when reducer changing the value it willn't affect the render if type is object, but that object will be different from previous one (values will change) – Zak the Gear Sep 18 '20 at 14:16
1 Answers
1
You have your reducer function wrong, CounterReducer.js, Line 10
return {
...state,
// don't set this directly, this code preserves the reference to the array and react does not updates the
counter: state.counter
// counter: Array.from(state.counter)
};
Check the code I have updated, you are setting the reference in the above code, replace the above code with this.
return {
...state,
//counter is now a new array
counter: [...state.counter]
// counter: Array.from(state.counter)
};

Sudhanshu Kumar
- 1,926
- 1
- 9
- 21
-
1
-
1It's called spread operator, more here, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax – Sudhanshu Kumar Sep 18 '20 at 14:48
-
Sure, thank you again, I was know it but not used too much. So here it is needed for object to be converted in elements so it will go in props and will be like an array. But how did you get your decision, meaning how did you know you need to use it here? Just want to get the logic of using this operator in redux. – Zak the Gear Sep 18 '20 at 14:52
-
1It's not a decision, This is a general rule of thumb and whole react's setState and view updation is based on this You never change your array or object directly, You modify them and return the new array/object, so that react knows that it must update the view since state was updated, must read this https://stackoverflow.com/a/40309023/8155208 – Sudhanshu Kumar Sep 18 '20 at 15:00