Вопрос

React documentation says

Don't worry about precomputing values based on state — it's easier to ensure that your UI is consistent if you do all computation within render().

http://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html

This makes perfectly sense when the computations are small.

But I'm storing the bunch of large arrays in this.state for data visualizations I'm rendering on SVG. I have to compute several values based on those. The thing is that those computations are fairly heavy and it is impossible to compute those always within render.

So, how should I go about caching those computations while ensuring that I don't get inconsistent state with this.state and those computed variables?

Это было полезно?

Решение

I think I've figured it out.

I moved the large arrays to the state of the parent component and I'll just pass them as props to the visualization component. Then I just compute the values in componentDidMount and componentWillReceiveProps and save them into the state of the visualization component.

This avoids most of the useless computing in my case. But if it is not enough I can go further and diff the current props with the next props in componentWillReceiveProps to determine if the computation is actually needed.

UPDATE: Now that I've worked more with React I think this should be done using memoizing. Reselect is good lib for that.

Другие советы

I tried some data visualization with React and SVG as well, and did not have any performance problem yet. React only rerender on state change, or parent component's state change so those computations are not run very often.

If in your case the components are updating frequently, you can try memoize the computing functions with lodash.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top