Use toSorted() Instead of sort() for Immutability
Install this skill
npx skills add vercel-labs/agent-skillsWorks across Claude Code, Cursor, Codex, Copilot & Antigravity
The standard JavaScript sort() method modifies the underlying array instance directly, leading to side effects that often disrupt state management patterns in React or data-heavy applications. By switching to toSorted(), developers generate a shallow copy of the original array while applying the sorting logic, preserving the source data. This approach prevents accidental data mutation, which is a common source of bugs when dealing with props or global state containers. Because toSorted() produces a new reference, it ensures that equality checks and memoization hooks perform predictably. This implementation is particularly vital for maintaining functional programming integrity in modern codebases where data flow is unidirectional. By replacing destructive sorting patterns with this non-mutating alternative, you avoid unintended state synchronicity issues and improve the maintainability of your component logic across complex application states.
When to Use This Skill
- •Displaying sorted lists derived from component props
- •Sorting arrays stored in Redux or Zustand state
- •Processing API responses before local component rendering
- •Creating derived state views without modifying cached backend data
How to Invoke This Skill
Example prompts that trigger this skill in Claude Code, Cursor, or Antigravity:
- “How do I sort an array without changing the original?
- “Fix state mutation issues in React sorting
- “Use non-mutating sort in JavaScript
- “Convert sort() to immutable version
- “Prevent React prop mutation during sorting
What this skill does
- •Generates a new array instance from existing data
- •Preserves original array order and reference
- •Accepts custom comparator functions for complex sorting
- •Ensures compatibility with React immutability requirements
- •Reduces side-effect bugs in data-processing pipelines
When not to use it
- ✕When strictly optimizing for performance in memory-constrained legacy environments
- ✕When working in environments older than Node.js 20 or pre-2023 browser versions without a polyfill
Example workflow
- Identify an array being sorted within a render function or hook
- Remove the existing .sort() method call
- Replace it with .toSorted() using the same comparator logic
- Verify that the original source data remains untouched
- Check component re-renders to ensure reference equality triggers correctly
Prerequisites
- –Node.js 20+ or modern browser environment
- –Understanding of array reference vs value
Pitfalls & limitations
- !Does not support legacy browsers without polyfills
- !Creating frequent shallow copies can affect performance with extremely large datasets
- !Implicitly assumes the user understands that the original array reference remains unchanged
FAQ
How it compares
While manual copying with the spread operator achieves immutability, toSorted() is more readable and explicitly defines the developer's intent to return a new data structure.
📄 Full skill instructions — original source: vercel-labs/agent-skills
.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.**Incorrect (mutates original array):**
function UserList({ users }: { users: User[] }) {
// Mutates the users prop array!
const sorted = useMemo(
() => users.sort((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}**Correct (creates new array):**
function UserList({ users }: { users: User[] }) {
// Creates new sorted array, original unchanged
const sorted = useMemo(
() => users.toSorted((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}**Why this matters in React:**
1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
**Browser support (fallback for older browsers):**
.toSorted() is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:// Fallback for older browsers
const sorted = [...items].sort((a, b) => a.value - b.value)**Other immutable array methods:**
-
.toSorted() - immutable sort-
.toReversed() - immutable reverse-
.toSpliced() - immutable splice-
.with() - immutable element replacementHow to Use This Skill Unit
Option A: Project-Specific (Recommended)
- Click "Download" above
- In your project, create the directory:
.agent/skills/js-tosorted-immutable/ - Save the file as
SKILL.md - The agent will automatically discover the skill based on its description.
Option B: Global Installation (All Agents)
Save the file to these locations to make it available across all projects:
- Claude Code:
~/.claude/skills/vercel-labs/agent-skills/js-tosorted-immutable/SKILL.md - Cursor:
~/.cursor/skills/vercel-labs/agent-skills/js-tosorted-immutable/SKILL.md - Antigravity:
~/.gemini/antigravity/skills/vercel-labs/agent-skills/js-tosorted-immutable/SKILL.md
🚀 Install with CLI:npx skills add vercel-labs/agent-skills