Since this is my first post I just have to open it with “Don’t judge book by it’s cover”, just hear me out.
Problem
I have to be honest, deepcloning objects can be really messy. Sure, it is easier with some packages like loadesh, but when you do that “by the hand”, it’s hard to track what you did or didn’t copy, especially when big complex objects are in play.
Oh sorry, I forgot to explain why we have to clone objects in order to update them, and I can do that in just one word: immutability. Huh, okey, that was easy :) I’m kidding. Since I don’t know my audience yet, I will try to be as clear as blue sky, so let’s get more technical.
Immutability
Immutability is very important part of every react application. Component in react app is rendered based on props and state. When props or state changes (by this I mean when reference to the object is changed), components rerenders. It’s that simple.
When working with complex object which contain 3 or more levels of objects for e.g, and you want to change some property on third level, you need to copy that object where property lives, it’s parent, then parent’s parent. And that’s it, I think…? You see my point. Let’s say we have done that right, now we have an old unchanged object and a new copied object with just one property changed. Now, state can be updated and component rerenders! Hooray!
All that insecurity and potential bugs where your component didn’t update can be a result of badly managed immutability.
I hope I didn’t make you angry by this time but let’s get to the point.
Solution for all your problems
const user = {
firstName: “Branko”,
lastName: “Stančević”,
location: {
city: “Novi Sad”,
country: “Serbia”
}
}
const newUser = user;
Okay, now user and newUser have reference to the same object. If you try to do something like: user === newUser
you will get true, as expected.
To avoid all spreading and loadash deepcloning functionalities to make new copy of the object, we can simply do this:
const newUser = JSON.parse(JSON.stringify(user));
user === newUser
is no longer true, both of the constants have their own reference to the completly same data but different object. Even children objects don’t have same reference, hence you may do with that object whatever you want without worrying about immutability.
Simply pinpoint property in child object, change it and your job is done.
newUser.location.city = “Belgrade”;
Then with that updated object update your state or do whatever you want. :)
Conclusion
This idea can be explored furthermore, test performance against familiar processes of deepcloning is just one of the many roads that we can take together.
I’m frankly happy to hear out your thoughts on this topic good people.
Thank you for your time. I hope you have enjoyed reading this post :)
Top comments (0)