Shallow Copy vs Deep Copy

“setState() – eh? That’s not right.” – Shallow Copy vs Deep Copy

A quick summary and solution to a pass by reference vs pass by value bug that I found recently.

Tom hanks confused meme
setState() – eh? That’s not right.

TLDR;

Use lodash and the cloneDeep function to stop copying by reference errors in React.
let target = _.cloneDeep(sourceToClone)

Scenario

Imagine the situation, you’re about to ship your code to live and you run one last test, add a bunch of the same item to a page and edit one and boom they all update. You start pouring over your code, looking at every [‚ĶtheSpreadOperator], Object.assign() you can find but everything looks like it should be ok ‚Ķ

Assign by reference vs Assign by value (Shallow Copy vs Deep Copy)

Take a deep breath, you’ve hit one of Javascript’s quirks,  assign by reference or assign by value. It’s not obvious in javascript when you’re copying a reference (shallow copy) or copying by value (deep copy), typically if you copy an object or an array, you’re copying by reference. This is even harder to see when using a framework like react.
I just hit the same scenario and used lodash’s .cloneDeep() function to resolve it and thought that would be worth a share.

example

let target = _.cloneDeep(sourceToClone)

#ProblemSolved #BugFix

David

Big guy, beard, likes software development.