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?
Approach: Follow these simple steps in order to store single data into cache in ReactJS. We have created our addDataIntoCache function which takes the user data and store into the browser cache. When we click on the button, the function is triggered and data gets stored into the cache, and we see an alert popup.
When the user is typing in the search, there is no reason for the higher component to rerender, and thus the map component does not rerender. This suggests that the problem is the expensive function that hinders the application as a whole. The item list is defined when the component mounts in an UseEffect hook.
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.
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