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 is now {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) achieves the same result as the previous method, and this approach has several advantages:
Simplifying Complex Features#
Immutability makes complex features easier to implement. In the following sections, we will implement a feature called "time travel" in the tic-tac-toe game. "Time travel" allows us to review the history of moves in the game and "jump back" to previous steps. This feature is not only applicable to games - undo and redo functionality is a common requirement in development. Not directly modifying 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 thus determine when to re-render components.