top of page
Logo der Online Agentur mdwp

Mutation

In the context of React JS, mutation refers to the process of changing the data inside an object or variable, which in turn can lead to changes in the state of a React component. This is important in React because state changes can cause components to re-render, updating the UI.

In other words, mutation is the altering of data in an unpredictable manner which can potentially lead to bugs in application as React's re-render of components is based on the new state.

To avoid mutation, and therefore decrease the potential for bugs, React developers often use functions to create new altered copies of data rather than directly changing the original data.

Here is an example in code:

Bad practice (mutation):

```jsx
let person = {name: 'John', age: 28};

function celebrateBirthday(person) {
person.age++; // This mutates the object
}

celebrateBirthday(person);
console.log(person.age); // Outputs: 29
```

Good practice (no mutation):

```jsx
let person = {name: 'John', age: 28};

function celebrateBirthday(person) {
return {...person, age: person.age + 1}; // Creates a new object
}

let newPerson = celebrateBirthday(person);
console.log(newPerson.age); // Outputs: 29
console.log(person.age); // Outputs: 28 (original data is unchanged)
```

In the first example, we directly mutate the `person` object by adding 1 to its age property. In the second example, we return a new object which has all the same properties as `person`, but with an incremented age property. This leaves our original `person` object unchanged,a practice that is preferred in many cases in order to avoid unexpected side effects.

bottom of page