top of page
Logo der Online Agentur mdwp

Immutability

Immutability in React Js refers to the practice where data is never directly changed or modified once it's created. This means that if you need to change a state based on the previous state, you should not directly modify the original one; instead, you should create a new copy of the object, modify the new copy, and then set the new copy as the new state.

Immutability helps in maintaining code predictability, traceability, and performance optimization, especially in larger applications. Specifically, in react, it helps in optimizing the re-rendering process and offers other features like time-travel debugging.

In mostly modern JavaScript applications, you will come across the following pattern often when dealing with arrays or objects.

For example to add an item to an existing list:

```
// original data
let list = [1, 2, 3, 4, 5];

// A wrong (mutable) approach
list.push(6);

// A correct (immutable) approach
let newList = [...list, 6];
```

In the above example, instead of pushing item 6 directly into the original array (which is mutable way), we spread out the original array to a new array and added the new item into the new array, thus not modifying the original array.

Remember, favoring immutability will help you build out applications that are easier to optimize, debug, test, and maintain.

bottom of page