Back to JavaScript Performance

Use toSorted() Instead of sort() for Immutability

javascriptarraysimmutabilityreactstatemutation
28.0k🕒 2026-06-10Source ↗

Install this skill

npx skills add vercel-labs/agent-skills

Works 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

  1. Identify an array being sorted within a render function or hook
  2. Remove the existing .sort() method call
  3. Replace it with .toSorted() using the same comparator logic
  4. Verify that the original source data remains untouched
  5. 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

Why does sort() cause bugs in React?
React relies on referential equality to determine if state or props have changed. Mutating an array in place keeps the same reference, causing React to skip necessary re-renders.
Is there a performance difference between sort() and toSorted()?
toSorted() performs a copy operation first, so it is slightly slower and uses more memory than an in-place sort. However, the safety benefits usually outweigh this overhead.
What should I do if my target browser does not support toSorted()?
Use the spread operator syntax [...array].sort(comparator) to achieve the same immutable result in older environments.
Does toSorted() handle deep object comparison?
It performs a shallow copy of the array elements. If the elements are objects, the objects themselves are still references, though the array order is handled immutably.

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.

Source & trust

28k stars🕒 Updated 2026-06-10
📄 Full skill instructions — original source: vercel-labs/agent-skills
## Use toSorted() Instead of sort() for Immutability

.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 replacement

How to Use This Skill Unit

Option A: Project-Specific (Recommended)

  1. Click "Download" above
  2. In your project, create the directory: .agent/skills/js-tosorted-immutable/
  3. Save the file as SKILL.md
  4. 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

Read the Master Guide: Mastering Agent Skills

Recommended Rules

View more rules

Recommended Workflows

View more workflows

Recommended MCP Servers

View more MCP servers

Take It Further

Maximize your productivity with these powerful resources

📋

Define Your Standards

Set up coding standards to ensure this workflow produces consistent, high-quality results.

Browse Rules Library
📖

Master Workflows

Learn how to create custom workflows, use Turbo Mode, and build your automation library.

Complete Guide

How to use this Skill in Claude Code & Cursor

For Claude Code (CLI)

To use this skill in Claude Code, copy the rule content into your project's custom instructions or follow our Add-Skill CLI guide. This ensures Claude follows your standards during every code generation.

For Cursor & Windsurf

For Cursor or Windsurf, individual skills are best used in the "Rules for AI" section. This specific unit helps the agent avoid javascript performance issues, leading to cleaner, more efficient code.

Why the skill format matters: the standardized Agent Skills format lets your AI agent load detailed instructions only when they are relevant, keeping your prompt clean while improving results.

Source & attribution

This skill is categorized under JavaScript Performance and is published by Vercel Engineering, maintained in vercel-labs/agent-skills.

← Browse All Agent Skills
Sponsored AI assistant. Recommendations may be paid.