toSorted
An array method that returns a sorted copy and leaves the original unchanged, unlike sort, which reorders the array in place.
In more detail
Sorting a prop or state array with sort mutates it and breaks purity; toSorted, or slice().sort(), sorts a copy. toSorted is part of ECMAScript 2023.
Example
const sorted = items.toSorted((a, b) => a.price - b.price);Related terms
- mutation — A change to data, and in TanStack Query or tRPC specifically, a request that creates, updates or deletes data on the server.
- pure function — A function whose result depends only on its arguments and which has no side effects, so the same inputs always give the same output.
Taught in
- Component Purity: Pure Functions, Idempotence And Side Effects — React 19 & Modern Component Architecture
- The React Compiler: Automated Memoization Under The Hood — React 19 & Modern Component Architecture