What Are Immutable Objects?
The definition of mutable is “liable or subject to change or alteration.” When discussing programming, we use it to indicate objects that are allowed to change over time. So, conversely, an immutable value is the opposite – after that object is first created, it cannot be changed. It is not variable.
Basically… immutable objects means that you are always creating new objects (or entire data structures) as opposed to making individual changes to those existing objects in the original data structure.
Why Are Immutable Objects Used?
The main reason for immutable objects is that they are thread safe. This makes sense in some languages.
Performance is debatable for immutable objects. They use a larger memory footprint but in some situations can reduce the number of processes. The most important performance issue for a model though is its impact on DOM rendering.
But When Applied to React.js Apps…
Facebook’s React.js is a popular view framework – that’s the V in MV*. It also has a library for models called Immutable.js.
For React apps, it makes some sense to use Immutable.js. React uses the
Observer Pattern to update the View on a change to its Model.
Whether you like React or not, there is some simplicity in not having to write specific binds between the Model and View. And the expensive process of observing all objects isn’t impacted by replacing the entire Model through Immutable.js. React creates a simplified, virtual DOM and compares this to the actual one to see if any updates need to be made.
Sometimes native objects make more sense for React apps, not just for performance, but because you can use native arrays with a much more extensive list manipulation library like lodash.