Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply 62 React and Next.js performance optimization rules from Vercel Engineering
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
rules/js-tosorted-immutable.md
1---2title: Use toSorted() Instead of sort() for Immutability3impact: MEDIUM-HIGH4impactDescription: prevents mutation bugs in React state5tags: javascript, arrays, immutability, react, state, mutation6---78## Use toSorted() Instead of sort() for Immutability910`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.1112**Incorrect (mutates original array):**1314```typescript15function UserList({ users }: { users: User[] }) {16// Mutates the users prop array!17const sorted = useMemo(18() => users.sort((a, b) => a.name.localeCompare(b.name)),19[users]20)21return <div>{sorted.map(renderUser)}</div>22}23```2425**Correct (creates new array):**2627```typescript28function UserList({ users }: { users: User[] }) {29// Creates new sorted array, original unchanged30const sorted = useMemo(31() => users.toSorted((a, b) => a.name.localeCompare(b.name)),32[users]33)34return <div>{sorted.map(renderUser)}</div>35}36```3738**Why this matters in React:**39401. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only412. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior4243**Browser support (fallback for older browsers):**4445`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:4647```typescript48// Fallback for older browsers49const sorted = [...items].sort((a, b) => a.value - b.value)50```5152**Other immutable array methods:**5354- `.toSorted()` - immutable sort55- `.toReversed()` - immutable reverse56- `.toSpliced()` - immutable splice57- `.with()` - immutable element replacement58