Reputation: 358
Does Deep copying objects when developing with react a must practice? or will a shallow copy method like Object.assign() be sufficient?
Upvotes: 3
Views: 1635
Reputation: 5435
React does not enforce/recommend either method. react does not care. Is your data flow architecture which usually dictates how your state should be treated. i.e Redux do heavily advocate for immutable data structures most commonly achieved through the use of immutableJS. In general the use of immutable data structures is advised specially since they are multi thread safe and remove errors by accidental updates. But react it self does not care about it. In this particular one can be react,angular, vue or the next one immutable structures will always be cleaner and safer to use and should be used if your architecture allows it
Upvotes: 0
Reputation: 7688
Object.assign will create creates deep copy for one level only. It creates shallow copy of its childs. Using shallow copy and passing references is problematic when you play with nested components.
Answering to your question, using deep-copy is suggested instead of Object.assign as if you are passing any property which is an object to child component, the changes in this child object will not reflect to child component as it is shallow copy. In some cases, shallow copy will not trigger change detection.
Best way is you can use immutable pattern.
Upvotes: 1
Reputation: 2754
Shallow copy is actually preferred, because it indicates that some of the property values have not changed.
Upvotes: 0