In JavaScript, when working with objects or arrays, especially within React components, we often need to take a copy of the current state or variable.
Many of us use the spread operator (...)
for this purpose. While this is great for creating shallow copies, it falls short when it comes to deep copies, which can lead to unintended behavior. Let’s understand this with an example.
Problem: The spread operator only creates a new reference for top-level properties. Since arr
is a nested, so it is referenced in both obj
and obj_copy
changes made in obj_copy
affect the original obj
object as well.
To solve this problem, we need a deep copy. There are a few ways to achieve this:
Libraries like Lodash: You can use libraries such as Lodash (_.cloneDeep)
to handle deep copies.
JSON Methods: A common approach is using JSON.stringify()
and JSON.parse()
to create a deep copy:
Using third-party libraries for deep cloning adds extra weight to your bundle, Instead of relying on libraries or using the JSON methods, structuredClone is a native, efficient way to deep clone JavaScript objects, introduced in recent versions of modern browser
While the spread operator is handy for creating shallow copies, it falls short for deep cloning nested objects or arrays. Modern JavaScript provides a built-in, efficient solution in the form of structuredClone()
, which ensures that objects are properly copied without unexpected reference sharing. This makes structuredClone()
a perfect fit for use cases where immutability is crucial, such as state management in React applications.
That’s it for now! Thanks for reading. See you in the next post!
Source link
lol