What is Immer.js and Immutability?
Immer.js is an increasingly popular tool for reinforcing immutable data structures in React. Immutability refers to an unchangeable, unalterable state. It's important to ensure that immutability is properly enforced, even when using Redux.
That's because it is possible to mutate the Redux store, resulting in bugs and issues. Immutability libraries like immer.js and immutable.js exist to provide an extra layer of strength behind already stable Redux containers. This ensures beyond a doubt that states accurately update, protecting against otherwise possible mutations.
Top 3 Benefits of Using Immer.js
On a recent web application development project at Praxent, an Austin-based Inc. 5000 company, software developer Peter Elbaum evaluated the risks and made the informed decision to use immer.js instead of the default, immutable.js.
When asked what drew him to immer.js over immutable.js, he offered two main reasons:
1. Simpler API
Immer’s API is easy-to-use. Peter only had to review the documentation a few times to grasp the core concepts. This stands in stark contrast to the steep learning curve involved in mastering immutable.js.
Immer.js, on the other hand, is fairly easier to learn. It solves the same problems as immutable.js, but in a more streamlined and efficient manner.
3. Great for Writing Redux Reducers & Tests
Immer.js syntax provides a clear expression of outputs and inputs, which means developers can avoid most object creation and destructuring.
Unfortunately, this caused state mutation and bugs in Peter's project that were difficult to diagnose. This was partly due to compatibility issues with Praxent's React boilerplate, which uses OOP to model database resources.
Positive Results with Immer.js
When put to the test, immer.js proves to be a solid option for reinforcing immutability in React. It removes the need for complicated string paths, offering a simple, streamlined alternative to immutable.js.