Redux is just a data store. As such, in its purest sense, redux doesn't really need either immutability or deep cloning to work as a concept.
However, redux requires immutability in order to work well with UI frameworks that build on top of it (such as React).
For this simple reason: What parts of my state have changed between the last time a framework looked?
Given that goal, can you see how deep-cloning actually doesn't help? If you look at one object that has been deep cloned, then every sub-part of that object is now different in terms of identity (===
).
As a concrete example, if you run the following code:
const bookstore = { name: "Jane's books", numBooks: 42 };
const reduxData = { bookstore, employees: ['Ada', 'Bear'] };
And now let's say you want to change just the number of books you have at the bookstore.
If you did a deep copy, like so:
const reduxClone = JSON.parse(JSON.stringify(reduxData));
reduxClone.bookstore.numBooks = 25;
Then you would 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 re-render everything to see if anything has changed.
The correct solution is to use a simple rule of immutability. If you change a value of an object, you have to create a new copy of that object. So, since we want a new numBooks, we need to create a new bookstore. And since we have a new bookstore, we need to make a new redux store.
const newBookstore = Object.assign({}, bookstore, {numBooks: 25});
const shallowReduxClone = Object.assign({}, reduxData, {bookstore: newBookstore});
Now, you'll see that the bookstores have changed (yay!), but the employees have not (double yay!)
console.log(reduxData.bookstore === shallowReduxClone.bookstore); // returns false
console.log(reduxData.employees === shallowReduxClone.employees); // returns true
I hope this example helps. Immutability allows you to change the least amount of an object when making changes. If you guarantee you'll never change an object, then you can reuse that object in other trees that you build up. In this example, we were able to use the employees
object twice, without danger, because we promised to never mutate the employees object.