Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-redux: What is the difference between state.setIn() and state.set()?

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?

like image 568
Matthias M Avatar asked Dec 23 '15 11:12

Matthias M


People also ask

Why state is immutable in Redux?

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.

How does Redux compare 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 is state immutable in React?

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.

Why mutations are prevented in reducer states?

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.


1 Answers

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.

like image 85
hazardous Avatar answered Sep 20 '22 17:09

hazardous