Redux: Don't mutate. But Do Reuse.

When I started learning Redux, I thought I had to clone my whole state tree before changing it in my reducer function. But this is not true (and is bad for performance).

But I wasn't sure how to reuse parts of the old state without "mutating".

After learning more, I think I see a practical version of the "don't mutate" rule which is:

The Rule: Code that starts with a reference to the old state object can never be allowed to see any changes.

Therefore, if you will change something somewhere out on a branch of the state tree, all of the change's parent objects must be new. (So, the root of the new state tree is always a new object.)

But, branches without changes can be reused. Because code starting from the old root can safely traverse onto those branches because they contain nothing new.

And the above also means that children of a changed node can be reused, as long as those branches have no other change.

Of course, this all depends on your state actually being a tree. Otherwise, it's much more complicated. So, make sure your state is a tree. Not a random graph. Maybe a DAG, if you want to think really hard. But I don't want to think that hard. So I will just make it a tree.

PS: Making sure that my state is a tree probably means I will have to use some IDs, instead of object references, when I want data to be "on" multiple branches

PPS: I'll update this with any additions or corrections I find. And please comment below if I got anything wrong. Thanks!


Comments

Popular posts from this blog

Callback, Promise, Observable, and Doughnuts

Learn grid and grid-template-areas FIRST!!!

The Day TDD Started Working for Me