What is Immutable Data?
Simply data that can not be changed is immutable.
In the example below, we have data array which contains no of hours one employee worked on some specific project.
var hoursWorked = [8, 8, 8, 7, 7, 9, 6, 8, 8, 7]; console.log(hoursWorked); //op: [8, 8, 8, 7, 7, 9, 6, 8, 8, 7] lets check last 5 days of work var lastFiveDays = hoursWorked.slice(0,5); console.log(lastFiveDays); //op: [8, 8, 8, 7, 7] awesome //let me sort the hourseWorked var sortedHoursWorked = hoursWorked.sort(); console.log(
); //op: [6, 7, 7, 7, 8, 8, 8, 8, 8, 9] Perfect var lastSixDays =
);//op: [6, 7, 7, 7, 8, 8] ohh No
[8, 8, 8, 7, 7, 9] expected.
In above the example, we have used 2 different methods, slice, and sort.
Slice is an immutable way as it did slice the original object and sent the new copy to the lastFiveDays Object. It helped us to regain the original copy of the dataset as well.
Sort is a mutable way as it sorted the original dataset. It blocked us to make further calculations on the dataset.
What are the benefits of Immutability?
According to react documentation.
Easier Undo/Redo and Time Travel
when you are working on the complex object. In case Object is mutable one step/statement can change the structure or value of the object and later operation may lead incorrect data. Immutable data helps here.
Determining When to Re-render in React
This point is regarding when to update the view of your page. If we have different copies of the object we can decide if 2 objects are changed then we will update. We need something to take a decision on otherwise we will keep updating the vie whenever some event has fired.
Looking for React JS Development Company, Hire our dedicated developers!