Hiprup

What is immutability and why does it matter?

Immutability means not changing data after it's created — instead, you produce new values with the changes.

  • How — copy then modify (spread, map, filter) rather than mutating in place.

  • Why — predictable state, easier debugging, and reliable change detection.

Critical in frameworks like React, where state updates must create new references to trigger re-renders.

// Mutable (avoid)
const user = { name: 'John', age: 30 };
user.age = 31; // Mutates existing object

// Immutable (preferred)
const updatedUser = { ...user, age: 31 }; // New object
console.log(user.age);        // 30 (unchanged)
console.log(updatedUser.age); // 31 (new object)

// Immutable array operations
const items = [1, 2, 3];
const added = [...items, 4];                    // Add
const removed = items.filter(x => x !== 2);     // Remove
const updated = items.map(x => x === 2 ? 20 : x); // Update

// Deep immutability with Object.freeze
const config = Object.freeze({
  api: 'https://api.example.com',
  timeout: 5000
});
// config.api = 'new'; // Silently fails (TypeError in strict)

// Immer for complex immutable updates
import { produce } from 'immer';
const next = produce(user, draft => {
  draft.age = 31;           // Looks mutable
  draft.address.city = 'LA'; // Deep update
}); // Returns new immutable object

Spread creates a new object with overrides. Array methods (filter, map, spread) create new arrays without mutating.

Object.freeze prevents changes (shallow). Immer lets you write mutable-looking code that produces immutable results (used by Redux Toolkit).

Why: predictability, React performance (shallow comparison), undo/redo. How: spread for objects/arrays, filter/map for array operations, Object.freeze for protection.

Immer for complex nested updates (Redux Toolkit uses it). Mutations are the #1 source of React bugs.

What is immutability and why does it matter? | Hiprup