QUESTION: What is immutability?
Immutability in JavaScript is a programming concept according to which a created object, array, or primitive cannot be modified after its creation. If a developer needs to update some data in such an object, they do not mutate the initial state directly.
Instead, an absolutely new object is created, into which the old properties are copied and only those fields that require changes are overwritten. In practice, this is implemented using the spread operator.
For this, a simple syntax like const newObj = { ...obj, key: newVal } is used, which allows assembling a new object in a fraction of a second. At the same time, the old object is preserved unchanged for state history or debugging.
Manually creating deep copies of complex data structures can be tedious and error-prone, so developers often use specialized libraries for convenience. A great example is the Immer library, which allows writing code as if you are modifying data directly, but creates immutable copies under the hood.
Adhering to the principle of immutability is critically important for modern state management libraries and frameworks, such as React and Redux. It is data immutability that allows components to instantly and without unnecessary overhead determine the fact of a state change by comparing object references, which directly affects rendering speed and user interface stability.