react.dev icon indicating copy to clipboard operation
react.dev copied to clipboard

New array methods

Open o-t-w opened this issue 2 years ago • 2 comments

Now that all browsers support the new array methods toSpliced(), with(), toSorted(), toReversed(), do they offer a better solution compared to the spread operator, worth documenting in the Updating Arrays in State page?

In the current docs:

const insertAt = 1; // Could be any index
    const nextArtists = [
      // Items before the insertion point:
      ...artists.slice(0, insertAt),
      // New item:
      { id: nextId++, name: name },
      // Items after the insertion point:
      ...artists.slice(insertAt)
    ];

Could be replaced with:

 setArtists(artists.toSpliced(1, 0, { id: nextId++, name: name }));

o-t-w avatar Jul 21 '23 07:07 o-t-w

Yes, I was thinking the same whilst reviewing the FR translation for that page.

If the team is interested, I'm willing to send a PR. I think just betting the farm on new methods isn't good enough (it would require polyfills for a large segment of the install base out there still), but just as we have a part about Immer, we could have small extra segments for each relevant use case that showcase the solutions with toSpliced(), with(), toSorted() and toReversed() for sure, and mention these would require polyfilling on older browsers, which is usually already set up with Babel's preset-env and core-js integration anyway (or through a service such as polyfill.io).

tdd avatar Jul 25 '23 19:07 tdd

I think they've been around long enough now. People can consult caniuse and make their own decisions.

o-t-w avatar Mar 27 '24 10:03 o-t-w