Skip to content
Inside a Developer's Head by Jesús Quintana, home

From JSX to pixels

Milestone: First paint

Lesson 4 of 249 min

In this lesson

So far in this course I have built three things that do not know about each other. Elements & JSX turns JSX into plain objects, and nothing draws them. Fiber tree walks a tree of fibers with a while loop, but I linked the fibers by hand and the walk only printed lines. DOM host creates and updates DOM nodes, but I called every function myself.

This lesson writes the glue. There is no new concept in it. At the end, createRoot(container).render(<App />) puts a tree of function components on the page, and we will have met the most important split in React: the render phase, which builds everything in memory, and the commit phase, which touches the page.

One question to keep in mind: the final demo has 31 DOM nodes. While they are being built, how many times does the page change?

The starting point

I copied the finished files of the three lessons into one folder, src/mini-react/:

  • from Elements & JSX: shared.ts, jsx-runtime.ts, jsx-dev-runtime.ts, index.ts;
  • from DOM host: dom-host.ts, and its shallowEqual helper pasted at the bottom of shared.ts;
  • from Fiber tree: fiber.ts and work-loop.ts.

In work-loop.ts I deleted the pause machinery (budget, shouldYield, workLoopConcurrent, and getWorkInProgress, which only reported where the walk had stopped). It comes back much later, with a real clock. I also changed its import from './fiber.ts' to './fiber': the Fiber tree lesson ran in Node, here a bundler resolves imports. The hand-built tree and the recursive walk stay behind.

What remains of the work loop is the cursor, the loop, and a beginWork and completeWork that only log. Those two are what gets replaced.

The plan is a pipeline with three arrows. Step through it here; each of the next sections steps through one part of it, next to its code.

The plan: three arrows from an element to the page
beginWorkcompleteWorkcommitRootelement<App />fiberDOM nodepage

  1. It starts with an element, the plain object JSX makes: <App />. Nothing draws it yet.
  2. beginWork turns elements into fibers: it reads each element’s type, calls the components and links the children they return.
  3. completeWork turns each fiber that stands for a tag or a text into a DOM node. The nodes are built detached: nothing is on the page yet.
  4. commitRoot puts the finished tree in the container. It is the only arrow that touches the page.

From an element to a fiber

An element has a type, a key and props. createFiber takes a tag, props and a key. The only thing missing is the tag, and the type decides it. At the bottom of fiber.ts (plus import type { Key, ReactElement } from './shared' at the top):

From an element to a fiber
beginWorkcompleteWorkcommitRootelement{ type, key, props }fiberDOM nodepage

  1. createFiberFromElement unpacks the element: its type, key and props become the arguments of createFiberFromTypeAndProps.
  2. A function as the type is a component, so the tag is FunctionComponent.
  3. A string is a DOM tag: HostComponent.
  4. Anything else is refused, the Fragment symbol included for now. There is no fiber to make, so it throws.
  5. createFiber makes the fiber with that tag, the props and the key. The fiber keeps the type: the tag name, or the function to call later.
  6. A string between two tags is not an element, so it has its own function. Its HostText fiber keeps the string as its props.
// Element -> fiber. The element says WHAT to render; its `type` decides the tag.
export function createFiberFromTypeAndProps(type: any, key: Key, pendingProps: any): Fiber {
  let tag: WorkTag;
  if (typeof type === 'function') {
    tag = FunctionComponent;
  } else if (typeof type === 'string') {
    tag = HostComponent;
  } else {
    throw new Error(`mini-react: unsupported element type: ${String(type)}`);
  }
  const fiber = createFiber(tag, pendingProps, key);
  fiber.type = type;
  return fiber;
}

export function createFiberFromElement(element: ReactElement): Fiber {
  return createFiberFromTypeAndProps(element.type, element.key, element.props);
}

/** A string between two tags is not an element. Its fiber keeps the string as its "props". */
export function createFiberFromText(text: string): Fiber {
  return createFiber(HostText, text, null);
}

A function is a component, a string is a DOM tag, anything else is refused (including the Fragment symbol, for now). Text is not an element at all, so it has its own function.

From children to linked fibers

In the Fiber tree lesson I wrote the child, sibling and return pointers by hand. This file writes them. Its input is a parent fiber and its children, which can be one element, a string, a number, an array, or nothing.

From children to linked fibers
beginWorkcompleteWorkcommitRootelementone child, or manyfiberDOM nodepage

  1. mountChildFibers gets a parent fiber and its children. An array goes to reconcileChildrenArray; anything else is one child.
  2. isElement reads the $$typeof symbol from Elements & JSX. An element becomes a fiber through createFiberFromElement.
  3. A non-empty string or a number becomes a text fiber.
  4. null, undefined, booleans and '' make no fiber. That is why {isAdmin && <Button />} draws nothing when isAdmin is false.
  5. Every new fiber points back to its parent with return, the pointer the Fiber tree lesson wrote by hand.
  6. For an array, flattened first, each child that makes a fiber is linked to the one before with sibling. The first one is returned and becomes the parent’s child. Grandchildren wait for their own beginWork.
import { type Fiber, createFiberFromElement, createFiberFromText } from './fiber';
import { REACT_ELEMENT_TYPE, type ReactElement } from './shared';

function isElement(x: any): x is ReactElement {
  return typeof x === 'object' && x !== null && x.$$typeof === REACT_ELEMENT_TYPE;
}
function isText(x: any): x is string | number {
  return (typeof x === 'string' && x !== '') || typeof x === 'number';
}

/** One child -> one fiber. null for the children that draw nothing. */
function createChild(returnFiber: Fiber, newChild: any): Fiber | null {
  let created: Fiber;
  if (isText(newChild)) created = createFiberFromText('' + newChild);
  else if (isElement(newChild)) created = createFiberFromElement(newChild);
  else return null; // null, undefined, true, false, ''
  created.return = returnFiber;
  return created;
}

/** Many children -> a chain of fibers. Returns the first one. */
function reconcileChildrenArray(returnFiber: Fiber, newChildren: any[]): Fiber | null {
  let resultingFirstChild: Fiber | null = null;
  let previousNewFiber: Fiber | null = null;
  // `<ul><li/>{items.map(...)}</ul>` puts an array inside the array: flatten it.
  for (const newChild of newChildren.flat(Infinity)) {
    const newFiber = createChild(returnFiber, newChild);
    if (newFiber === null) continue;
    if (previousNewFiber === null) resultingFirstChild = newFiber;
    else previousNewFiber.sibling = newFiber;
    previousNewFiber = newFiber;
  }
  return resultingFirstChild;
}

export function mountChildFibers(returnFiber: Fiber, newChild: any): Fiber | null {
  if (Array.isArray(newChild)) return reconcileChildrenArray(returnFiber, newChild);
  return createChild(returnFiber, newChild);
}

isElement is the first code that reads the $$typeof symbol from Elements & JSX. createChild returns null for null, undefined and booleans, which is why {isAdmin && <Button />} draws nothing when isAdmin is false. "Reconcile" means comparing two things; on a first render there is nothing to compare with, so this version only creates. Note that it builds one level and never looks at grandchildren.

The real beginWork

The Fiber tree lesson's beginWork returned fiber.child, which already existed. Now it has to create the children first, and what the children are depends on the tag.

The real beginWork: where the children come from
beginWorkcompleteWorkcommitRootelementfiberHostRootDOM nodepage

  1. beginWork gets the fiber under the cursor and switches on its tag: what its children are depends on it.
  2. For the root, the children are the element given to render, kept in the fiber’s memoizedState.
  3. For a component, the children are what the function returns. Component(nextProps) is the line that finally calls App.
  4. For a div, the children are props.children: they are elements already.
  5. reconcileChildren turns them into fibers with mountChildFibers and hangs the first on child. beginWork returns it, and the walk goes one level down.
  6. A text fiber has no children: beginWork returns null, and the walk turns around to completeWork.
import { type Fiber, FunctionComponent, HostComponent, HostRoot, HostText } from './fiber';
import { mountChildFibers } from './child-fiber';

export function beginWork(workInProgress: Fiber): Fiber | null {
  switch (workInProgress.tag) {
    case FunctionComponent:
      return updateFunctionComponent(workInProgress, workInProgress.type, workInProgress.pendingProps);
    case HostRoot:
      return updateHostRoot(workInProgress);
    case HostComponent:
      reconcileChildren(workInProgress, workInProgress.pendingProps.children);
      return workInProgress.child;
    case HostText:
      return null; // leaf
  }
  throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}

export function reconcileChildren(workInProgress: Fiber, nextChildren: any): void {
  workInProgress.child = mountChildFibers(workInProgress, nextChildren);
}

function updateFunctionComponent(workInProgress: Fiber, Component: (props: any) => any, nextProps: any): Fiber | null {
  // This is the line that calls your component.
  const nextChildren = Component(nextProps);
  reconcileChildren(workInProgress, nextChildren);
  return workInProgress.child;
}

function updateHostRoot(workInProgress: Fiber): Fiber | null {
  const nextChildren = workInProgress.memoizedState.element;
  reconcileChildren(workInProgress, nextChildren);
  return workInProgress.child;
}

For a div, the children are props.children. For a component, the children are whatever the function returns. In Elements & JSX a counter showed that writing <Greeting /> calls nothing; Component(nextProps) is the line that finally does. It is a plain call because there are no hooks yet. For the root, the children are the element given to render, read from the fiber's state.

The consequence: the fiber tree is no longer built before the walk. It is built by the walk, one level per beginWork.

The root and render()

A fiber does not know which DOM node to render into. That is the job of a second object, the FiberRoot:

import { type Fiber, HostRoot, createFiber } from './fiber';

export interface FiberRoot {
  /** The DOM node we render into. */
  containerInfo: HTMLElement;
  /** The HostRoot fiber: the top of this root's fiber tree. */
  current: Fiber;
}

export function createFiberRoot(containerInfo: HTMLElement): FiberRoot {
  const uninitializedFiber = createFiber(HostRoot, null, null);
  const root: FiberRoot = { containerInfo, current: uninitializedFiber };
  uninitializedFiber.stateNode = root;
  uninitializedFiber.memoizedState = { element: null };
  return root;
}

The Fiber class in fiber.ts gets one new field for this, next to pendingProps:

/** The fiber's own state. Only the HostRoot has one so far: { element }, what render() was given. */
memoizedState: any = null;

And the public entry point:

import { createFiberRoot } from './fiber-root';
import { performSyncWorkOnRoot } from './work-loop';

export interface Root {
  render(element: any): void;
}

export function createRoot(container: HTMLElement): Root {
  const root = createFiberRoot(container);

  const updateContainer = (element: any) => {
    const hostRootFiber = root.current;
    // The HostRoot's state is "the element I was asked to render".
    // updateHostRoot (begin-work.ts) reads it back.
    hostRootFiber.memoizedState = { element };
    performSyncWorkOnRoot(root);
  };

  return { render: updateContainer };
}

render stores the element where updateHostRoot reads it, then does all the work before returning. index.ts gains export { createRoot, type Root } from './root'.

completeWork makes DOM nodes

The Fiber tree lesson had a rule: a fiber completes only after all its children have completed. That makes completeWork the right place to create DOM nodes. When a div completes, its children's nodes already exist, so it can create itself and put them inside.

completeWork makes DOM nodes
beginWorkcompleteWorkcommitRootelementfiber#textDOM node"Hello"page

  1. The deepest fibers complete first. A text fiber gets a text node, kept in its stateNode.
  2. When h1 completes, createInstance makes the element: the whole DOM host lesson in one call.
  3. Its children completed earlier, so their nodes exist. appendAllChildren puts them inside, without going into them.
  4. The fiber keeps its node in stateNode, where its parent will look for it.
  5. Counter completes too, but a component has no DOM node of its own, and neither has the root.
  6. When div completes, the walk goes down through Counter to append its p, then climbs back and moves on to footer. The tree is built, still detached.
import { type Fiber, FunctionComponent, HostComponent, HostRoot, HostText } from './fiber';
import { createInstance, createTextInstance, appendChild } from './dom-host';

export function completeWork(workInProgress: Fiber): void {
  const newProps = workInProgress.pendingProps;
  switch (workInProgress.tag) {
    case FunctionComponent:
    case HostRoot:
      return; // no DOM node of their own

    case HostComponent: {
      const instance = createInstance(workInProgress.type, newProps);
      appendAllChildren(instance, workInProgress);
      workInProgress.stateNode = instance;
      return;
    }

    case HostText:
      workInProgress.stateNode = createTextInstance(newProps);
      return;
  }
  throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}

/** Append the top-level host nodes of the subtree (skipping components). */
export function appendAllChildren(parent: HTMLElement, workInProgress: Fiber): void {
  let node = workInProgress.child;
  while (node !== null) {
    if (node.tag === HostComponent || node.tag === HostText) {
      // A DOM node: append it. Do NOT go below it, its own children are already inside.
      appendChild(parent, node.stateNode);
    } else if (node.child !== null) {
      // A component: it has no DOM node. Its DOM nodes are further down.
      node = node.child;
      continue;
    }
    // Next: the sibling, or the sibling of the nearest ancestor that has one.
    while (node.sibling === null) {
      if (node.return === null || node.return === workInProgress) return;
      node = node.return;
    }
    node = node.sibling;
  }
}

createInstance is the whole of the DOM host lesson in one call: className, styles, the temporary click listener. appendAllChildren cannot simply loop over the child fibers, because a child may be a component, and a component has no DOM node. Its nodes are further down, so the function walks: append host nodes without going inside them, go down through components, then move to the sibling or climb return until there is one.

The work loop, and commitRoot

Here is work-loop.ts after the edits. The two logging functions are gone (their console.log lines moved into the loop, behind a flag), the loop starts from a FiberRoot, and there is one new function at the bottom.

The work loop, then commitRoot
beginWorkcompleteWorkcommitRootelementfiberDOM nodepagecontainer: []

  1. performSyncWorkOnRoot is two lines, and they are the two phases: render, in memory, then commit.
  2. The render phase points the cursor at the root fiber and loops until the cursor is null.
  3. Each unit of work is a beginWork. When it returns a child, the cursor moves down; when it returns null, the fiber completes.
  4. completeUnitOfWork runs completeWork, then moves to the sibling, or climbs to the parent and completes it too. At the end the cursor is null and the DOM tree exists, detached.
  5. commitRoot appends the finished tree to the container with appendAllChildren: one change to the document, and the page shows it.
import { getFiberName, type Fiber } from './fiber';
import type { FiberRoot } from './fiber-root';
import { beginWork } from './begin-work';
import { appendAllChildren, completeWork } from './complete-work';

/** LESSON ONLY: set `enabled` to print the walk, the same lines the Fiber tree lesson printed. */
export const walkLog = { enabled: false };

/** The cursor: the fiber we are about to work on. null = nothing left to do. */
let workInProgress: Fiber | null = null;

export function performSyncWorkOnRoot(root: FiberRoot): void {
  renderRootSync(root);
  commitRoot(root);
}

function renderRootSync(root: FiberRoot): void {
  prepareFreshStack(root);
  workLoopSync();
}

/** Start a walk: point the cursor at the top of a tree. */
export function prepareFreshStack(root: FiberRoot): void {
  workInProgress = root.current;
}

export function workLoopSync(): void {
  while (workInProgress !== null) performUnitOfWork(workInProgress);
}

function performUnitOfWork(unitOfWork: Fiber): void {
  if (walkLog.enabled) console.log(`begin    ${getFiberName(unitOfWork)}`);
  const next = beginWork(unitOfWork);
  if (next === null) completeUnitOfWork(unitOfWork);
  else workInProgress = next;
}

/** Complete this fiber, then move to its sibling, or complete the parent. */
function completeUnitOfWork(unitOfWork: Fiber): void {
  let completedWork: Fiber | null = unitOfWork;
  do {
    if (walkLog.enabled) console.log(`complete ${getFiberName(completedWork)}`);
    completeWork(completedWork);
    const sibling: Fiber | null = completedWork.sibling;
    if (sibling !== null) {
      workInProgress = sibling;
      return;
    }
    completedWork = completedWork.return;
    workInProgress = completedWork;
  } while (completedWork !== null);
}

function commitRoot(root: FiberRoot): void {
  const finishedWork = root.current;
  // The only line in the library that changes what the user sees.
  appendAllChildren(root.containerInfo, finishedWork);
}

performSyncWorkOnRoot is two lines, and they are the two phases. If you leave out the commitRoot(root) call and run a demo, the walk runs, every DOM node is created, and the page stays blank: the top div exists in memory with all its children, but it has no parent. commitRoot gives it one. It reuses appendAllChildren, this time with the real container as the parent.

index.ts also exports walkLog, a lesson-only switch.

The demo

The diagrams above take one function at a time. Here they run together: one walk over a small tree, a check of when the page changes, and a bigger app that leads into what this version cannot do.

First, the tree from the Fiber tree lesson, written as components:

function Counter() {
  return <p>Count: 0</p>;
}

function App() {
  return (
    <div>
      <h1>Hello</h1>
      <Counter />
      <footer />
    </div>
  );
}

walkLog.enabled = true;
createRoot(document.getElementById('root')!).render(<App />);
What it prints
begin    HostRoot
begin    App
begin    div
begin    h1
begin    #text
complete #text
complete h1
begin    Counter
begin    p
begin    #text
complete #text
complete p
complete Counter
begin    footer
complete footer
complete div
complete App
complete HostRoot

It prints 18 lines. Step through them below: each step prints a few and shows what they did to the fibers, the detached DOM and the container.

First paint, line by line

After the walk: workInProgress is null and nothing is detached any more, because the finished div with its h1, p and footer was appended to the container in one commit, so container.children holds that div. The log shows all 18 lines of the walk.

Variables

workInProgress
null
detachedTrees
[]
container.children
[<div>]

Log

begin    HostRootbegin    Appbegin    divbegin    h1begin    #textcomplete #textcomplete h1begin    Counterbegin    pbegin    #textcomplete #textcomplete pcomplete Counterbegin    footercomplete footercomplete divcomplete Appcomplete HostRoot

  1. From begin HostRoot to begin #text no fiber existed beforehand: each beginWork creates the children of the fiber it is on. updateHostRoot makes App from the element given to render, updateFunctionComponent calls App(props) and makes the div from what it returns, the div makes h1, Counter and footer in one go (the walk only begins h1 next), and h1 makes its text. Real React reconciles here too, with keys, moves and bailouts in the way; this version only creates.
  2. #text has nothing below it, so beginWork returns null and the walk turns around. completeWork calls createTextInstance: a text node Hello exists, with no parent. detachedTrees lists the DOM built so far that has no parent yet; the page has not changed.
  3. #text has no sibling, so completeUnitOfWork climbs to its parent and completes h1. createInstance makes the element, appendAllChildren puts the text node inside it and stateNode keeps it. A whole subtree exists in memory, attached to nothing. h1 does have a sibling, Counter, so the walk goes there next.
  4. Counter is the next sibling, so the walk goes down again: updateFunctionComponent calls Counter(), it returns a p, and the p gets its text. complete p builds <p>Count: 0</p>, but complete Counter builds nothing: a function component has no DOM node, so completeWork just returns. Two detached subtrees now.
  5. footer begins and completes in one go, then div completes. createInstance makes it and appendAllChildren collects its DOM children: the h1, then Counter, which is a component, so the walk goes down through it and appends its p, then footer. This is how the p reaches the div across the function fiber.
  6. App and HostRoot complete and create nothing: neither has a DOM node. The cursor is null, the render phase is over, and the whole page is one detached div. The document has not seen a single change.
  7. commitRoot calls appendAllChildren again, now with the real container as the parent: it walks down through App and appends the div. One insertion, which is why the MutationObserver prints the document saw 1 change(s) and added <div> with 3 elements inside. React also builds the DOM in completeWork and inserts it once at commit, but it marks the top fiber for placement during render and its commit phase does the insert, instead of appending the root's DOM children.
export function beginWork(workInProgress: Fiber): Fiber | null {
  switch (workInProgress.tag) {
    case FunctionComponent:
      return updateFunctionComponent(workInProgress, workInProgress.type, workInProgress.pendingProps);
    case HostRoot:
      return updateHostRoot(workInProgress);
    case HostComponent:
      reconcileChildren(workInProgress, workInProgress.pendingProps.children);
      return workInProgress.child;
    case HostText:
      return null; // leaf
  }
  throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}

export function reconcileChildren(workInProgress: Fiber, nextChildren: any): void {
  workInProgress.child = mountChildFibers(workInProgress, nextChildren);
}
function updateFunctionComponent(workInProgress: Fiber, Component: (props: any) => any, nextProps: any): Fiber | null {
  // This is the line that calls your component.
  const nextChildren = Component(nextProps);
  reconcileChildren(workInProgress, nextChildren);
  return workInProgress.child;
}

function updateHostRoot(workInProgress: Fiber): Fiber | null {
  const nextChildren = workInProgress.memoizedState.element;
  reconcileChildren(workInProgress, nextChildren);
  return workInProgress.child;
}
/** One child -> one fiber. null for the children that draw nothing. */
function createChild(returnFiber: Fiber, newChild: any): Fiber | null {
  let created: Fiber;
  if (isText(newChild)) created = createFiberFromText('' + newChild);
  else if (isElement(newChild)) created = createFiberFromElement(newChild);
  else return null; // null, undefined, true, false, ''
  created.return = returnFiber;
  return created;
}
export function mountChildFibers(returnFiber: Fiber, newChild: any): Fiber | null {
  if (Array.isArray(newChild)) return reconcileChildrenArray(returnFiber, newChild);
  return createChild(returnFiber, newChild);
}
export function completeWork(workInProgress: Fiber): void {
  const newProps = workInProgress.pendingProps;
  switch (workInProgress.tag) {
    case FunctionComponent:
    case HostRoot:
      return; // no DOM node of their own

    case HostComponent: {
      const instance = createInstance(workInProgress.type, newProps);
      appendAllChildren(instance, workInProgress);
      workInProgress.stateNode = instance;
      return;
    }

    case HostText:
      workInProgress.stateNode = createTextInstance(newProps);
      return;
  }
  throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}
/** Append the top-level host nodes of the subtree (skipping components). */
export function appendAllChildren(parent: HTMLElement, workInProgress: Fiber): void {
  let node = workInProgress.child;
  while (node !== null) {
    if (node.tag === HostComponent || node.tag === HostText) {
      // A DOM node: append it. Do NOT go below it, its own children are already inside.
      appendChild(parent, node.stateNode);
    } else if (node.child !== null) {
      // A component: it has no DOM node. Its DOM nodes are further down.
      node = node.child;
      continue;
    }
    // Next: the sibling, or the sibling of the nearest ancestor that has one.
    while (node.sibling === null) {
      if (node.return === null || node.return === workInProgress) return;
      node = node.return;
    }
    node = node.sibling;
  }
}
function performUnitOfWork(unitOfWork: Fiber): void {
  if (walkLog.enabled) console.log(`begin    ${getFiberName(unitOfWork)}`);
  const next = beginWork(unitOfWork);
  if (next === null) completeUnitOfWork(unitOfWork);
  else workInProgress = next;
}

/** Complete this fiber, then move to its sibling, or complete the parent. */
function completeUnitOfWork(unitOfWork: Fiber): void {
  let completedWork: Fiber | null = unitOfWork;
  do {
    if (walkLog.enabled) console.log(`complete ${getFiberName(completedWork)}`);
    completeWork(completedWork);
    const sibling: Fiber | null = completedWork.sibling;
    if (sibling !== null) {
      workInProgress = sibling;
      return;
    }
    completedWork = completedWork.return;
    workInProgress = completedWork;
  } while (completedWork !== null);
}
function commitRoot(root: FiberRoot): void {
  const finishedWork = root.current;
  // The only line in the library that changes what the user sees.
  appendAllChildren(root.containerInfo, finishedWork);
}

It is the order from the Fiber tree lesson, line for line, with four new lines in the middle: Counter is now really called, so the walk goes into the <p> it returned.

Now the question from the top. I put a MutationObserver on the container before rendering. With subtree: true it reports every node added anywhere below the container.

new MutationObserver((records) => {
  console.log(`the document saw ${records.length} change(s)`);
  for (const record of records) {
    for (const node of record.addedNodes) {
      const el = node as HTMLElement;
      console.log(`  added <${el.localName}> with ${el.querySelectorAll('*').length} elements inside`);
    }
  }
}).observe(container, { childList: true, subtree: true });
the document saw 1 change(s)
  added <div> with 3 elements inside

Eighteen lines of render phase, during which the document saw nothing, then one change. The page never shows a half-built tree, because a half-built tree is never in the document.

The final demo is closer to real code: props, a .map list of components, text mixed with elements, className, style, and a button.

The demo’s code
import { createRoot, walkLog } from 'mini-react';

const PIECES = [
  { id: 1, name: 'JSX makes elements' },
  { id: 2, name: 'beginWork makes fibers' },
  { id: 3, name: 'completeWork makes DOM nodes' },
];

function Piece(props: { id: number; name: string }) {
  return (
    <li className="piece">
      <b>0{props.id}</b> {props.name}
    </li>
  );
}

function Counter(props: { count: number }) {
  return (
    <p>
      Count: {props.count} <button onClick={() => render(props.count + 1)}>+1</button>
    </p>
  );
}

function App(props: { name: string; count: number }) {
  return (
    <div className="card" style={{ width: 320, padding: 16, border: '1px solid gray', borderRadius: 8 }}>
      <h1>Hello, {props.name}</h1>
      <ul>
        {PIECES.map((piece) => (
          <Piece key={piece.id} id={piece.id} name={piece.name} />
        ))}
      </ul>
      <Counter count={props.count} />
      <footer style={{ color: 'gray', fontSize: 12 }}>painted by mini-react</footer>
    </div>
  );
}

const container = document.getElementById('root')!;
// ...the MutationObserver from above goes here...

walkLog.enabled = false; // true prints every begin / complete
const root = createRoot(container);

function render(count: number) {
  root.render(<App name="Ada" count={count} />);
}

render(0);

No code was written for lists, props or styles, and it works: 37 fibers, 31 DOM nodes, and the console says

the document saw 1 change(s)
  added <div> with 11 elements inside

What goes wrong

Look at the demo’s +1 button. There is no state in this library, so the only way to show a different count is to call render again with new props. Click +1 and you do not get "Count: 1" in place. You get a second card under the first one. Click again, a third.

The second render did exactly what the first did: it called every component, created 36 new fibers and 31 new DOM nodes for a one-character change, and appended the result. Nothing removed the old card, because nothing remembers there was one. The old button is still there too, still holding count = 0.

This React can paint. It cannot repaint.

What we simplified

  • render() writes the element straight into the root fiber's memoizedState. Real React queues it as an update; the place it ends up is the same.
  • Everything is synchronous. There is no scheduler.
  • Keys are stored on fibers and never read. Nested arrays are flattened. Fragments throw.
  • Events still use the direct addEventListener shortcut from the DOM host lesson.
  • walkLog exists only so the walk can be printed.

Where this goes

To repaint, React has to compare the children it rendered last time with the ones it wants now, and decide which nodes stay, which move and which go. The next lesson, Keyed diff, builds that comparison alone, with no DOM. The Reconciler milestone then merges it into this folder, and calling render twice will do what you expect.