Mutative

1.3.0 · active · verified Sun Apr 19

Mutative is a JavaScript library designed for performing efficient immutable updates on data structures, drawing inspiration from libraries like Immer but with a strong focus on performance. It allows developers to write 'mutative' logic inside a producer function, and Mutative handles the underlying copy-on-write mechanism to return a new, immutably updated state. The library is currently at version 1.3.0 and exhibits an active release cadence, with frequent patch and minor updates. Key differentiators include its reported performance benefits, claiming to be 2-6x faster than naive handcrafted reducers using spread operators and over 10x faster than Immer, primarily through shallow copy optimization, lazy drafts, and an optimized finalization process. It aims to address issues like Immer's mandatory auto-freeze and improve type inference and handling of various immutability edge cases.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `create` to immutably update nested objects and arrays, showcasing efficient partial updates and reference preservation for unchanged parts.

import { create, original } from 'mutative';

interface TodoItem {
  id: number;
  text: string;
  completed: boolean;
}

interface AppState {
  todos: TodoItem[];
  filter: 'all' | 'active' | 'completed';
  user: { name: string; id: string };
}

const initialState: AppState = {
  todos: [
    { id: 1, text: 'Learn Mutative', completed: false },
    { id: 2, text: 'Build Something', completed: true },
  ],
  filter: 'all',
  user: { name: 'John Doe', id: 'user-123' },
};

// Update an item and add a new one
const newState = create(initialState, (draft) => {
  const todoToUpdate = draft.todos.find(todo => todo.id === 1);
  if (todoToUpdate) {
    todoToUpdate.completed = true;
    todoToUpdate.text = 'Learn Mutative (done!)';
  }
  draft.todos.push({ id: 3, text: 'Deploy App', completed: false });
  draft.user.name = 'Jane Doe';
});

console.log('Initial State:', original(initialState));
console.log('New State:', newState);
console.log('Are states different?', initialState !== newState); // true
console.log('Is todos array different?', initialState.todos !== newState.todos); // true
console.log('Are other parts (e.g., filter) unchanged by reference?', initialState.filter === newState.filter); // true
console.log('Original todo 1 text (from initial state):', initialState.todos[0]?.text); // Learn Mutative
console.log('New todo 1 text (from new state):', newState.todos[0]?.text); // Learn Mutative (done!)

view raw JSON →