Re:Why-did-you-update – Warnings about unnecessary React upd...
by acemarke on Wednesday April 19, 2017 @02:57PM
(#14150675)
Good explanation, with one nitpick: the diff is done between the _old_ virtual DOM tree and the _new_ virtual DOM tree, not between the virtual DOM tree and the real DOM. That's why you can have a component that renders a single div, and then get the reference to the real DOM node and use jQuery or some other DOM-manipulating library to attach non-React-based DOM elements to the div. As far as React knows, you're just telling it to keep rendering that same div, so nothing needs to change.
You have some data (props and state) that defines the current state of your program. This data is passed to a rendering function, which creates a virtual DOM representation of the component based on the data. After this has happened, the virtual DOM is diffed against the previously built virtual DOM to see if we should tell the browser to render the real DOM based on the new virtual one.
So the general cycle works like this:
Data was updated -> virtual render -> diff new virtual DOM vs old virtual DOM -> real render if necessary.
However, both constructing the virtual DOM as well as diffing the DOMs takes considerable amounts of time. That's why React offers a short-cut to avoid it, if necessary: shouldComponentUpdate. This lifecycle method is called after your data updates and before the virtual render takes place, allowing you to short-circuit the process if you already know that your data didn't change in a way that changes the resulting DOM.
So with the short-circuit, there are two general pathways. If you know the data didn't affect the DOM:
Data was updated -> return false in shouldComponentUpdate -> nothing more happens.
If you know the data affects the DOM or you're not sure:
Data was updated -> return true in shouldComponentUpdate -> virtual render -> diff new virtual DOM vs old virtual DOM -> real render if necessary.
The value of the tool is that it monkey-patches some React internals to notify you when you have missed a chance to use shouldComponentUpdate properly.