Skip to main content
rule CX Codex

js-tosorted-immutable — Claude Code rule

The js-tosorted-immutable rule replaces mutating .sort() with .toSorted(), keeping React props and state arrays unchanged during sorting.

MIT ★ 7,191 updated 2026-10-24

Install into Claude Code · Manually: put the files in place All methods and platforms ↓
.claude/rules/js-tosorted-immutable.md
Open on GitHub

What js-tosorted-immutable does

The rule directs Claude Code to use .toSorted() when an array needs ordering. Unlike .sort(), it returns a new sorted array and leaves the original value intact. That fits React’s read-only treatment of props and state.

It also addresses array changes inside callbacks and effects, where mutation can produce stale behavior. Older browsers and runtimes below Node.js 20 need a fallback such as [...items].sort((a, b) => a.value - b.value). Projects running Node.js 20+ can use .toSorted() directly.

What it helps with

  • replace in-place array sorting
  • keep React props unchanged
  • avoid stale arrays inside closures
  • rewrite user-list sorting safely

Example prompts for the agent

  • Review this React code and replace .sort() with a non-mutating sort.
  • Rewrite the users list sorting without changing the props array.
  • Check whether this project needs a fallback for .toSorted().

How to install js-tosorted-immutable

Manually: put the files in place

.claude/rules/js-tosorted-immutable.md

The paths frontmatter field limits the files

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about js-tosorted-immutable

How do I install js-tosorted-immutable in Claude Code?

Place .claude/rules/js-tosorted-immutable.md in the project.

What does js-tosorted-immutable do?

It tells the coding agent to prefer .toSorted() over .sort(), so sorting returns a new array instead of changing the original. The rule targets mutation problems involving React props, state, callbacks, and effects.

What is the fallback for older runtimes?

Copy the array before calling .sort(), as in [...items].sort((a, b) => a.value - b.value). .toSorted() is available in Chrome 110+, Safari 16+, Firefox 115+, and Node.js 20+.

Source text

js-tosorted-immutable.md · MIT
---
title: Use toSorted() Instead of sort() for Immutability
impact: MEDIUM-HIGH
impactDescription: prevents mutation bugs in React state
tags: javascript, arrays, immutability, react, state, mutation
---

## 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):**

```typescript
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):**

```typescript
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:

```typescript
// 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

© tech-leads-club · MIT · tech-leads-club/agent-skills

Similar IDE rules

All IDE rules for Frontend and UI →

From the same set130

The whole set →
client-passive-event-listeners client-passive-event-listeners instructs the agent to add { passive: true } to touch and wheel listeners, preventing scroll stutter in browser viewports. CX Codex +1 ★ 7,191repo stars js-cache-storage js-cache-storage keeps localStorage, sessionStorage and cookie values in memory so reads stop hitting synchronous browser storage. CX Codex +1 ★ 7,191repo stars rerender-use-ref-transient-values The rerender-use-ref-transient-values rule teaches the agent to store frequently changing values in useRef instead of useState to avoid re-rendering the component on every update. CX Codex +1 ★ 7,191repo stars js-length-check-first js-length-check-first — a rule for Claude Code that prompts the AI to check array lengths before running expensive operations like sorting or deep equality checks. If lengths differ, arrays cannot be equal—no expensive work needed. CX Codex +1 ★ 7,191repo stars patterns-children-over-render-props patterns-children-over-render-props — a Claude rule that pushes React components toward composition with children instead of renderX props, so call sites read as plain JSX. CX Codex +1 ★ 7,191repo stars js-cache-function-results js-cache-function-results instructs the agent to cache repeated function calls using a module-level Map. It eliminates redundant computations across renders and utility calls. CX Codex +1 ★ 7,191repo stars client-localstorage-schema The client-localstorage-schema rule guides Claude Code to version localStorage keys and keep only fields the UI needs. Use it when changing client-side settings or cached user data. CX Codex +1 ★ 7,191repo stars client-event-listeners client-event-listeners — a Claude rule that keeps a single keydown listener on window no matter how many components call the shortcut hook. CX Codex +1 ★ 7,191repo stars

Project sponsors

Companies that keep this analytics open