This was originally posted as a gist and shared with people in ReactDC here: https://gist.github.com/kimagure/79b0aed0d90641726b91
The default behavior of React is actually not very fast.
This is especially the case when you have a list or table with lots of elements to represent data. Most of the data may not be changing, but the portions that do will need to get data passed down from the parent. But since the parent needs to render all the siblings of the changed element, having React reuse render()
results on the siblings that haven't changed is very useful.
Good React Components are functions of only their props and state, and in those cases you will inevitably end up going through the same render()
calls which are unnecessary and they provide the same output.
Luckily, with shouldComponentUpdate
, you can make React skip wasteful extra render()
calls. By comparing your components' previous and current props/state, you can tell React to skip computation of entire trees' worth of elements and cut down and cost.
But how do you do a performant comparison between props and state? Doing a true deep comparison between the previous and current props/state might take just as long as it does to just call render()
again on the component. This is when using immutable data can help.
If we can just do comparisons of object references, that's going to be a lot faster than trying to do deep compares. But this does require discipline on your part -- you're not longer allowed to change values when you do this. Instead, every time you make a change, you need to invalidate the object reference by assigning a new object to replace the old object.
I hope you'll find this interactive demo a good introduction to using shouldComponentUpdate
and immutable data. Once you feel comfortable with the ideas presented here, try using the provided modules in React:
- React.addons.update (react/lib/update) -- immutability helper for making controlled changes to a data structure
- React.addons.PureRenderMixin (react/lib/ReactComponentWithPureRenderMixin) -- mixin for doing shallow data comparisons with
shouldComponentUpdate
for rendering "pure" components
Demo:
References:
https://facebook.github.io/react/docs/pure-render-mixin.html
https://facebook.github.io/react/docs/update.html