about immutability

May 26, 2024

When I think about immutability nowadays, I mostly focus on how it is used in frameworks and state management libraries.

In frameworks like Angular, immutability helps update the UI efficiently, which is one of the core concepts. When properties are sent through @Input decorator, the object's reference must be changed; otherwise, these changes wil not make change detection to rerender the view.

Immutability gives us a lot of benefits, such as:

  • Strict control over the data that doesn't change allows developers understand and manage data flows and code changes more easily.
  • Modern engines are highly optimized for immutable patterns, excessive creation of short-lived objects (be careful, it can still lead to performance issues).
  • In store libraries, immutability allows to track changes that happened like chain of events, thanks to time travel, undo/redo features, optimistic updates and rollbacks, which also makes debugging a lot easier.

On the other hand:

  • Copying objects increases memory usage and slows down performance, but to make copying more efficient, we can use structural sharing, as many redux-like libraries requires to do, like NgRx. More about this pattern you can read here.