According to the official documentation, the concept of immutability is very important in React for two main reasons. Generally, there are two ways to change data. The first way is to directly modify the value of a variable, and the second way is to replace the old data with a new copy of the data.
Generally, there are two ways to change data. The first way is to directly modify the value of a variable, and the second way is to replace the old data with a new copy of the data.
Directly Modifying Data#
var player = {score: 1, name: 'Jeff'};
player.score = 2;
// The value of player after modification is {score: 2, name: 'Jeff'}
Replacing Old Data with New Data#
var player = {score: 1, name: 'Jeff'};
var newPlayer = Object.assign({}, player, {score: 2});
// The value of player remains unchanged, but the value of newPlayer is {score: 2, name: 'Jeff'}
// Using object spread syntax, it can be written as:
// var newPlayer = {...player, score: 2};
Not directly modifying (or changing the underlying data) has the same result as the previous method, and this method has the following advantages:
Simplifying Complex Features#
Immutability makes complex features easier to implement. In the following sections, we will implement a feature called "time travel" in which we can review the history of moves in a tic-tac-toe game and "jump back" to previous moves. This feature is not only used in games - undo and redo functionality is a common requirement in development. Not directly modifying the data allows us to trace and reuse the game's history.
Tracking Changes in Data#
If data is directly modified, it becomes difficult to track changes in the data. Tracking changes in data requires mutable objects to be compared with their previous versions, which requires traversing the entire object tree.
Determining When to Re-render in React#
The main advantage of immutability is that it helps us create pure components in React. We can easily determine if immutable data has changed, and therefore determine when to re-render components.