Using Immer to Optimise Redux Reducer | by Vinay Mittal | Mar, 2022

Picture by Clark Tibbs on Unsplash

We are going to cowl the under subjects on this publish:

  • Introduction to immer
  • Use circumstances of immer in our codebase and implementation
  • How and after we ought to use immer
  • Advantages of immer

Immer is a tiny bundle that permits you to work with immutable state in a extra handy means. Immer can be utilized in any context the place we wish to obtain immutability. For instance together with React state, React or Redux reducers, or configuration administration.
The phrase immutable means unchanging over time or unable to be modified. Javascript objects are mutable in nature however with immer we will obtain immutability. Let’s perceive this with an instance:-

Within the above instance, we’ve used a produce methodology that’s uncovered by immer. The syntax of produce is:

produce(baseState, recipe: (draftState) => void): nextState

produce takes a base state, and a recipe that can be utilized to carry out all the specified mutations on the draft that’s handed in.

The attention-grabbing factor about Immer is that the baseState can be untouched, however the nextState will replicate all adjustments made to draftState. So, we’ve a model new state i.e. nextState and there’s no any dependency of baseState on this.

We’re utilizing immer produce methodology to optimize reducer file code. Let’s examine what’s the issue with out immer with a code snippet:

So, right here we’ve a reducer referred to as UPDATE_STREETNO_VISIBILITY for updating streetno visibility. The issue is with showStreetNo which is deeply nested contained in the response object, consequence right here. To retrieve the worth, we’ll have to make use of the unfold operator a number of instances – And that does not look good.

In JavaScript, objects are mutable — updating properties of a state object straight on the reference doesn’t change the thing as an entire.

Due to this fact, it’s normally really useful to all the time return a brand new state object from the reducer.

We are able to obtain immutability utilizing immer which helps in optimizing code as nicely.

Let’s examine with the code snippet:

Let’s implement withProduce methodology:

As we will see, we’ve a withProduce methodology that’s calls reducer when an motion get dispatched with draftState .
The produce perform receives one argument, the draft, which is a proxy to the present state you handed in. Any modification you make to the draft can be recorded and used to provide nextState. The currentState can be untouched throughout this course of.

We now have optimized code in UPDATE_STREETNO_VISIBILITY reducer as there isn’t a must make a brand new state object and preserve references with the unfold operator.

Merely entry the state with the dot operator and replace the worth.
Immer produce does all of the work like sustaining references and updating the worth.

Working of immer

More Posts