Redux is just a data warehouse. Thus, in the purest sense, redux really needs neither immutability nor deep cloning to work as a concept.
However, redux requires immutability to work well with user interface infrastructures that are built on top of it (like React).
For this simple reason: What parts of my state changed the last time the structure looked?
Given this goal, can you see how deep cloning really doesn't help? If you look at one object that has been deeply cloned, then each sub-part of this object is now different from its identity ( === ).
As a concrete example, if you run the following code:
const bookstore = { name: "Jane books", numBooks: 42 }; const reduxData = { bookstore, employees: ['Ada', 'Bear'] };
Now let's say you want to change only the number of books you have in the bookstore.
If you made a deep copy, for example:
const reduxClone = JSON.parse(JSON.stringify(reduxData)); reduxClone.bookstore.numBooks = 25;
Then you will see that both the bookstore and the employees are now different:
console.log(reduxData.bookstore === reduxClone.bookstore); // returns false console.log(reduxData.employees === reduxClone.employees); // returns false, but we haven't changed the employees
This is a problem because it looks like everything has changed. And now React has to redisplay everything to see if something has changed.
The correct solution is to use a simple rule of immutability. If you change the value of an object, you need to create a new copy of this object. So, since we need new numBooks, we need to create a new bookstore. And since we have a new bookstore, we need to create a new redux store.
const newBookstore = Object.assign({}, bookstore, {numBooks: 25}); const shallowReduxClone = Object.assign({}, reduxData, {bookstore: newBookstore});
Now you will see that the bookstores have changed (yay!), But the employees do not (double yay!)
console.log(reduxData.bookstore === shallowReduxClone.bookstore); // returns false console.log(reduxData.employees === shallowReduxClone.employees); // returns true
Hope this example helps. Invariance allows you to change the smallest number of objects when making changes. If you guarantee that you will never modify an object, you can reuse this object in other trees that you create. In this example, we could use the employees object twice, without danger, because we promised never to mutate the employees object.