Immutability and Mutability in JavaScript
In JavaScript data can be changed in two ways: mutably and immutably. Understanding difference between them is especially important when working with state in React, Redux and other libraries.
Mutability
Mutability means object can be changed after creation.
const user = { name: "Alice" };
user.name = "Bob"; // change directly
console.log(user); // { name: "Bob" }
Such changes happen by reference and can cause unpredictable behavior, especially if same object is used in multiple places
Immutability
Immutability means object doesn't change, and when changes occur new copy is created.
const user = { name: "Alice" };
const updatedUser = { ...user, name: "Bob" }; // create new object
console.log(user); // { name: "Alice" }
console.log(updatedUser); // { name: "Bob" }
Immutability makes data predictable and safe for comparison, which is critical when re-rendering components in React.
Immutability in React
React doesn't track changes by object content, it compares them by reference (===).
Therefore mutable update won't trigger re-render:
// wrong approach
state.items.push("newItem");
setState(state); // same reference → React won't update component
Correct immutable way:
// create new array
setState({ ...state, items: [...state.items, "newItem"] });
Comparison
| Property | Mutability | Immutability |
|---|---|---|
| Data change | Made directly in object | New copy is created |
| Behavior in React | May not trigger re-render | Always reliably triggers re-render |
| Data safety | Side effects possible | Data protected from mutations |
| Debugging convenience | Harder to track | Easier to track changes |
Immutable Operation Examples:
// arrays
const newArr = [...oldArr, newItem];
const filtered = oldArr.filter(item => item !== target);
// objects
const newObj = { ...oldObj, updatedKey: newValue };
// nested objects
const updated = {
...state,
user: {
...state.user,
name: "John",
},
};
Conclusion:
Use immutability to make code predictable, safe and compatible with React. This is foundation of correct work of useEffect, React.memo, Redux and other tools.