Quick note on React internal
— web dev — 2 min read
Given this block of React codebase
const element = <h1 title="foo">Hello</h1>const container = document.getElementById("root")ReactDOM.render(element, container)
Step 1. Convert JSX to an object (using Babel and a method called React.creatElement).
The result is an object that looks like this
const element = { type: "h1", props: { title: "foo", children: "Hello", },}
Step 2. The element
object will then be passed to render
.
Step 3. The render method recursively creates DOM nodes for the element
and its children
.
- The whole process will be done in multiple batches to avoid hogging the main thread. https://github.com/facebook/react/issues/11171#issuecomment-417349573. (aka Concurrent mode)
- The data structure behind the scene that stores all the "batches" is called a Fiber tree.
Step 4. Once the DOM tree is ready, it's committed to the real DOM. The Fiber tree will also be kept as a reference for the next step.
Step 5. On subsequent updates, steps 1 to 3 are repeated again, the new Fiber tree will then be compared with the existing Fiber (this process is called Reconciliation https://reactjs.org/docs/reconciliation.html), the differences will be committed to the DOM.