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?
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.
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.
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