top of page
Logo der Online Agentur mdwp


Immutability, in the context of React JS, refers to the practice of setting values that cannot be altered or modified once they're defined. This is an important concept in React JS because manipulating the state directly in React is a no-no and can lead to unexpected app behavior, hence, the idea of immutability.

To achieve immutability in React, you always want to make sure that you're dealing with new copies of the state and then let the React engine take care of the updates. The state itself is considered the single source of truth and it should not be tamely changed.

Here's a simple code example:

// BAD practice
this.state.myArray.push('new value');

// GOOD practice
let newArray = [...this.state.myArray, 'new value'];
this.setState({myArray: newArray});

The first example represents a mutable operation since it directly modifies the existing "myArray" object. The second example, however, is an immutable operation because it creates a brand new array with the new value, and then assigns this new array to the "myArray" property of the state.

bottom of page