556
Bn
bees-nest / files
bees-nest / .opencode / skills / vercel-react-best-practices / rules / js-tosorted-immutable.md
1.7 KB
1--- 2title: Use toSorted() Instead of sort() for Immutability 3impact: MEDIUM-HIGH 4impactDescription: prevents mutation bugs in React state 5tags: javascript, arrays, immutability, react, state, mutation 6--- 7 8## Use toSorted() Instead of sort() for Immutability 9 10`.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. 11 12**Incorrect (mutates original array):** 13 14```typescript 15function UserList({ users }: { users: User[] }) { 16 // Mutates the users prop array! 17 const sorted = useMemo( 18 () => users.sort((a, b) => a.name.localeCompare(b.name)), 19 [users] 20 ) 21 return <div>{sorted.map(renderUser)}</div> 22} 23``` 24 25**Correct (creates new array):** 26 27```typescript 28function UserList({ users }: { users: User[] }) { 29 // Creates new sorted array, original unchanged 30 const sorted = useMemo( 31 () => users.toSorted((a, b) => a.name.localeCompare(b.name)), 32 [users] 33 ) 34 return <div>{sorted.map(renderUser)}</div> 35} 36``` 37 38**Why this matters in React:** 39 401. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only 412. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior 42 43**Browser support (fallback for older browsers):** 44 45`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator: 46 47```typescript 48// Fallback for older browsers 49const sorted = [...items].sort((a, b) => a.value - b.value) 50``` 51 52**Other immutable array methods:** 53 54- `.toSorted()` - immutable sort 55- `.toReversed()` - immutable reverse 56- `.toSpliced()` - immutable splice 57- `.with()` - immutable element replacement