Created: 2021-11-24 19:58
Notes from Build your own React
createElement
React’s createElement
creats an object representing the element to be rendered:
const element = createElement(
"h1",
{ title: "foo" },
"Hello"
)
const element = {
type: "h1",
props: {
title: "foo",
children: "Hello",
},
}
The resulting tree is traversed by ReactDOM.render
to, well, render the elements into the DOM.
Concurrent mode
A single render pass would be too expensive and could block the browser, so a work loop is used which consist of creating units of work and doing each unit on requestIdleCallback
.
function workLoop(deadline) {
let shouldYield = false
while (nextUnitOfWork && !shouldYield) {
nextUnitOfWork = performUnitOfWork(
nextUnitOfWork
)
shouldYield = deadline.timeRemaining() < 1
}
requestIdleCallback(workLoop)
}
requestIdleCallback(workLoop)
At the moment concurrent mode isn’t enabled as it’s not safe (is that still the case?)
Fibers
The units of work are called fibers and kept track of in a tree.
Each fiber represents the work required to render a single element (or component?). Fibers are processed one at a time.
The fiber tree keeps links to the fiber’s first child, its next sibling and its parent. This way it’s easier to find the next unit of work.
How the fiber tree is traversed to find the next unit of work
To avoid rendering parts of the tree prematurely while the others aren’t ready, the entire fiber tree is only commited to the DOM when the whole tree is traversed.
Reconciliation
After the first render, any changes in the state trigger re-renders.
Traversing the whole thing again and adding everything to the DOM would be bad for performance.
Instead the fiber tree is diffed against the old one and only the necessary patches are applied.
Hooks, or state
The state setter, from useState
, triggers a re-render for the current component and down the tree.
The callback passed to it queues up an action that will actually happend on the re-render, before rendering. As opossed to happen immediatelly when the setter is called. Actions are queued up to all be performed together.
Whereas React itself has a ton of optimizations, the article builds a simplified version for didactic purposes. It paints a pretty accurate picture of how React works and all the moving pieces involved.