Cookies

With your permission, we use Google Analytics cookies to measure visits and improve the site. Necessary cookies are always on. You can change your choice or withdraw consent anytime in the footer, under Cookie settings. Cookie Policy

Skip to content

js-tosorted-immutable

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

  • Skills
  • Web development
  • 1

What it does and how to use it

A skill that teaches Claude Code to do web development tasks well. It is packaged knowledge the model uses whenever it is relevant.

  1. Install the skill (command above).
  2. In Claude Code, describe what you need - the skill turns on by itself when the context fits.
  3. No commands to memorize: you talk in plain language and the skill does the rest.

Install (Claude Code)

mkdir -p .claude/skills/js-tosorted-immutable && curl -fsSL https://doutorai.pt/data/lib/skills__js-tosorted-immutable.md -o .claude/skills/js-tosorted-immutable/SKILL.md

Paste this command into the terminal, in your project folder, and the component installs automatically.

Content

---
title: Use toSorted() Instead of sort() for Immutability
impact: MEDIUM
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

- 🔒 Full content on the Pro plan (€7.99/month) -

Need help with Claude Code?

Ask Dr AI - it explains things simply.

Need a tailor-made solution?

Not sure where to start with AI in your business? Get a free assessment and a tailored plan - no commitment.

Save hours every week with AI, no hassle

Doutor AI gives you 1,859 ready-to-copy AI prompts, by industry and in plain English - plus a complete technical library for those who want to go further.

See plans