This post is part of a series about React, Redux, Immutable.js and Flow
Two of the three Redux principles are “State is read-only” and “Changes are made with pure functions”. When changing the read-only state, you are not allowed to mutate the existing object: You are supposed to create a new object.
But this new object can share the parts that have not changed with the previous state.
immutable.js gives you several immutable data structures: Map, List, Set, Record and more. Those data structures cannot be changed once created.
You can use
get to get some value from the immutable data structure, and
getIn to get a deeply nested value. Using the
immutable object from above, this is how it works:
You can also run other functions that you would expect to work on collections, like
reduce and others.
OK, and now comes the interesting part. You can update those immutable data structures, but that will not modify them. Whenever you “update” one of these data structures, you get back a new object, and you can think of it as a complete copy of the old one, with the updated value modified (this is not how it works internally, see below).
When you need the previous value to calculate the new value of a field, you can use
update, which takes a function as an argument that calculated the new value based on the old value.
And if you want to set or update deeply nested values, you can use
And this Performs Well?
Yes. The immutable data structures try to copy as little as possible when doing mutable updates. They are implemented as trees that can share all the stuff that has not changed.
In exchange for that slight slowdown, you get a lot of safety. When you have immutable data, you can be sure it is unchanged, even when time has passed. And there are also some potential speed-ups: You never have to deeply compare data structures. If it is still the same object (pointer), the data is un-changed.
Immutable data structures can help you add safety to your programs. And when you use Redux, writing your reducers correctly will be easier and less error-prone when you use them.
Also, this blog post was only a very quick overview of immutable.js and what you can do with it. If you want to learn more, check out the official site.