I want to learn more about performance in React, so I'm trying to get a sense of exactly how and when React manipulates the DOM.
Stepping through the source (or inspecting in the devtools profiler), I can see that scheduleFlush is finally called when React triggers an update to the DOM. I understand how reconciliation works, but I'm looking for the actual mechanics (read: specific line of code) where React appends new elements to the DOM (e.g. rootElement.appendChild(newElement)). Can someone point me in the right direction?
I asked this on the #reactjs freenode, but didn't get the response I was looking for. Thanks in advance!
Most of the heavy lifting is here: https://github.com/facebook/react/blob/master/src/renderers/dom/fiber/ReactDOMFiberComponent.js ReactDOM injects it's a "host" component class into React. React itself handles the traversal and diffing, then calls the various update methods on ReactDOMFiberComponent, which does all the work of moving the host node (DOM node) to it's new markup.
@jquense Exactly what I was looking for -- thank you!
I would note that realistically in big React apps it's rarely the DOM manipulation that ends up being expensive. It's mostly reconciliation. That's why React offers strategies to avoid it (like PureComponent) and encourages use of virtualization for large lists.
@gaearon Thanks for that. That makes sense.
The question I've been trying to answer is, 'When a small component in a vastly larger component tree needs to be updated, how (literally) does React update it in the DOM?"
The question arose as I was reading about reconciliation, and I wondered if, when there are, say, 5 leaf components that require updating, does React replace the top-level root node (e.g. w/ replaceChild) with the updated root element and allow the browser to rebuild the render tree accordingly, or does React perform individual mutations to the the leaf elements directly?
I ask because I can imagine scenarios where either approach could present a performance bottleneck.
Excuse me if I'm asking the wrong questions here, or if this is well documented somewhere. So far I haven't come across anything to answer my question though.
No, React only updates the leaf nodes in this case.
Please see:
https://reactjs.org/docs/rendering-elements.html#react-only-updates-whats-necessary
Most helpful comment
Most of the heavy lifting is here: https://github.com/facebook/react/blob/master/src/renderers/dom/fiber/ReactDOMFiberComponent.js ReactDOM injects it's a "host" component class into React. React itself handles the traversal and diffing, then calls the various update methods on ReactDOMFiberComponent, which does all the work of moving the host node (DOM node) to it's new markup.