Insight #3 - Use ImmerJS over lodash/set, ImmutableJS or plain JS
Sebastien Lorber
Posted on June 11, 2020
ImmerJS is a very useful tool for React immutable mutations, that you can write with an imperative style.
I prefer ImmerJS to other tools for some reasons.
Plain vanilla JS: as soon as we start to deal with nested objects or array insertions/deletions, it starts to become unreadable. Here's a simple screen to show the issue, but the more you nest, the more it becomes difficult to deal with plain JS immutable updates, even with the new ES6 syntaxes that makes it more easy.
Lodash/set: using a string path like users[1].firstName
is not very typesafe. If we need to update multiple parts of the object at once, we'll likely need to create many intermediate state copies, which is not very performant.
ImmutableJS: unless you need to optimize for writes on a very large immutable list (in which case you'll benefit from a tree-based datastructure), you'd rather avoid this library.
This library does not use any JS primitive type like array/object, so you'll need to convert from/to primitive types regularly.
To avoid opting out of React.memo
and PureComponent
React component optimizations, you'll need to take care of preserving object identities by memoizing aggressively the toJS()
transformations (for Redux users, often done in mapState
using Reselect).
The library's abstraction is likely to leak in many places of your codebase. Do you really want to have ImmutableJS specific code in your state, your reducers, your connexion functions (mapState
for Redux users), or in your components, making it hard to migrate away from it if you want to use another tool?
records and tuples proposal: immutable data structures at stage-1 proposal.
This is one of the most exciting JS proposal right now, and it's worth a full blog post to cover all the benefits it would bring.
If this proposal is accepted, browser vendors could decide to implement it with an optimized tree-based structure to leverage the same kind of performances for writes than ImmutableJS.
Also, updating immutable objects might become simpler, as shawn in this tweet from ImmerJS author Michael Weststrate
Before, with Immer:
After: with records and tuples
Conclusion
Unless there's a standart JS immutable data structure implementation, I think it's safer to stick to plain objects/arrays.
Immer is the best solution for immutable updates, but it may change soon with records and tuples.
Part of my Insights serie (I try to write short/daily posts).
Follow me on Twitter, Dev, or check my website
Posted on June 11, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.