3

Does Deep copying objects when developing with react a must practice? or will a shallow copy method like Object.assign() be sufficient?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Shallow copy is actually preferred, because it indicates that some of the property values have not changed.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.