State Immutability
State updates should create new object or array references instead of mutating existing state. This makes changes predictable and lets UI frameworks detect updates through reference changes.
State immutability means treating existing state values as read-only. When state contains an object or array, an update should produce a new object or array rather than changing the existing value in place.
This matters because many frontend systems use reference identity to determine whether data changed. For example, changing `user.name` directly keeps the same `user` reference, while `{ ...user, name: "Ana" }` creates a different reference.
For arrays, use operations that return new arrays, such as `map`, `filter`, or spread syntax. Avoid mutating methods such as `push`, `pop`, `splice`, and direct index assignment when working with state.
Immutability does not mean every value in an application must be permanently unchangeable. It means that when updating state, you replace the relevant state value with a new value instead of modifying the existing state object or array.
Key points
- Treat existing state objects and arrays as read-only.
- Create new references when updating state.
- Use non-mutating array operations such as `map`, `filter`, and spread syntax.
- Avoid direct property changes, `push`, `pop`, and `splice` on state.
- Reference changes make state updates easier for UI frameworks to detect and reason about.
Interview questions
How would you update an object in state without mutating it?
Create a new object with the existing properties and overwrite the property that changed. In JavaScript, object spread is a common approach, such as `{ ...user, name: "Alex" }`. The original object remains unchanged and the new object has a different reference.
How do you update an array in state immutably?
Use operations that return a new array instead of changing the existing array. For example, `map` can replace an item, `filter` can remove items, and spread syntax can add items. Methods such as `push` and `splice` mutate the original array and should generally be avoided for state updates.
What does state immutability mean in frontend development?
It means treating existing state objects and arrays as read-only. When state needs to change, create a new object or array containing the updated data. This preserves the old reference and gives the UI framework a clear new value to work with. Common techniques include object spread and non-mutating array methods.
Why can mutating state cause rendering or update-detection problems?
A framework or state-management system may compare references to determine whether a value changed. If an object is mutated in place, its reference remains the same even though its contents changed. That can prevent an update from being detected by code relying on reference equality. Replacing the value with a new reference makes the change explicit.