Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using redux with immutable-js - do you call toJS() on your selector? Or do you use .get('prop') in the render function?

Right now I'm using reselect to create my selectors to extract data from the store and pass it to the props via connect. For simplicity, the result of my selectors is always a JS object (calling toJS() at the end of the selector), something like this:

const selector = state => state.get('data').toJS();

Now I'm trying to improve some performance and I realized that shouldComponentUpdate shallow comparison loses the advantages of immutability because of the way I'm returning from my selectors.

On the other hand, using .get('prop') inside my html seems extremely annoying:

<div>{this.props.data.get('prop')}</div>

Especially if I have a case of passing a simple JS object to a child component which is mutable, like this:

<ChildComponent totalItems={10} />

And then there is no consistency when accessing the props (some are mutable and some are immutable).

I thought of creating an helper unwrap function, something like this:

const unwrap = obj => obj && obj.toJS ? obj.toJS() : obj;

But I don't really like this solution.. I don't really like any of those approaches.

What do you use for both clean code & performance?

like image 774
Adam Tal Avatar asked Oct 19 '22 03:10

Adam Tal


2 Answers

To pass props to component collect all data under a key as immutable.

<MyComponent propsKey={Immutable.fromJS({someData: {key: "value"}})} />

To use benefits of Immutable you should avoid from use toJS(). It is very costly and you cannot use useful Immutable functions with that. Until you reach "value", you should use Immutable.get(). It is annoying at first but, you can see how it is useful and easy to use, in time. (To get inner keys using getIn() can be less annoying than chain get functions). In this way your code can work more efficient and you do not need to use unwrap function, in your component you guarantee your data under this.props.propsKey always immutable.

like image 92
Dilek Gencer Avatar answered Oct 21 '22 01:10

Dilek Gencer


You should wrap your presentational components in a simple higher-order component that calls toJS() on any Immutable.js object props passed to it.

This will give you the best balance of keeping the performance benefits of Immutable.js whilst keeping your container components from re-rendering too much, as well as keeping your presentational components dependency-free and therefore easily reusable and testable.

The Redux docs have a good selection of best practises for using Immutable.js, in particular, when not to use .toJS(), why your presentational components should be kept pure and how a "toJS" higher-order component might be defined and used.

like image 36
Matt Read Avatar answered Oct 21 '22 01:10

Matt Read