I've seen the use of setIn()
and set()
in some react-redux code:
state.setIn(...);
state.set(...);
I've found some documentation here https://facebook.github.io/immutable-js/ But unfortunately the method is not documented in detail.
I also found some other questions: Using React's immutable helper with Immutable.js But these do not answer my question.
I understand, that it must do some immutable stuff?
But what's the immutable thing here?
And what's the difference between set()
and setIn()
?
Why do we need immutable?
Immutability of redux state is necessary since it allows detecting redux state changes in an efficient manner. This implies that whenever we want to modify a redux state, we must create a new copy of it and do modifications to that copy - which then becomes the new redux state.
Redux uses shallow equality checking in its combineReducers function to return either a new mutated copy of the root state object, or, if no mutations have been made, the current root state object.
Why Immer works well for React State Immutability? In React, using an Immutable state enables quick and cheap comparison of the state tree before and after a change. As a result, each component decides whether to re-rendered or not before performing any costly DOM operations.
If you mutate the old object's property inside a reducer, the “new state” and the “old state” will both point to the same object and Redux will infer that nothing has changed.
Immutable set
method only sets immediate properties, I.e. direct children of the object. A setIn
let's you set the value of any deep node down the data. set
only takes property name. setIn
takes an array of keys/index to reach down to the deeply nested element.
var basket = Immutable.Map({"milk":"yes", "flour":"no"});
basket = basket.set("flour", "yes");
basket = Immutable.Map({"fruits":{"oranges":"no"}, "flour":"no"});
basket = basket.setIn(["fruits", "oranges"], "yes");
The getIn
/setIn
methods are extremely useful when updating states in stores as you can use generic actions and supply the key paths to child components. They can invoke the actions passing the paths as parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With