Hacker News new | ask | show | jobs
by lambda_garden 906 days ago
I've never had the need to clone anything in a real JS code-base, personally.

What's the use-case?

4 comments

It is very frequently needed when you're working with a component framework like React or Vue. Typically leaf components shouldn't mutate properties directly but rather emit a changed version of the original data they receive.

But it's not necessarily related to frameworks; if you're working with complex enough data structures and you're following a functional approach, you'll need to do similar things sooner than later.

I use React.

Why does that require deep clones?

I simply do:

    return {
      ...current
      foo: "bar"
    };
I'm not sure if you're asking why deep copies are useful or something else.

Maybe you're handing over your data to a library developed by someone else and you want to make sure the library cannot mutate your original data, so you opt to pass a deep copy instead. Or maybe you are the author of said library and you want to make sure you preserve the original data so you copy it on input rather than on output.

There are many situations where deep-copying is useful but I agree that you should use the simplest pattern that works for your use-case.

if "current" is a deep object here and contains other objects/arrays, you risk that wherever you are sending this shallow copy will mutate those deeper values and potentially mess things up for the code where "current" came from.

Maybe it's not a situation that comes up often, but it would be fairly hard to debug and guarding yourself against mysterious problems in advance is always neat.

In practice, I think it's easier to use linting and type-systems to prevent other code from mutating you stuff than defensive copying.
You could make the same argument backwards though - many people may find it easier to do deep copies rather than throwing extra software they might not necessarily be familiar with.
When the caller passes you a deep structure and you want to ensure they don't mutate it afterwards. But I agree, it's seldom needed in application code.
I came across a bug recently where a data structure from Redux, which is immutable, was passed to a GraphQL library that would modify the data it was passed. So we had to make a deep clone.
Every time you get an object from somewhere, which needs to be preserved and modified at the same time.