From JSX to pixels
DOM host
Lesson 3 of 246 min
In this lesson
A button re-renders. Its props are a brand-new object, and the style inside is
a brand-new object too. How many times should the DOM be written? If nothing
visible changed, the honest answer is zero, and getting to zero takes some code.
A second question sits right next to it. React Native runs the same components on a phone that has no DOM. How can one library do both?
Both answers are the same small file. In this lesson I write it: about a hundred lines that create DOM nodes, write props onto them, link them together, and work out the minimum change between two sets of props. No JSX, no components, nothing else from React. I will call the functions by hand.
Creating nodes
import { shallowEqual } from './shared';
export function createInstance(type: string, props: any): HTMLElement {
const el = document.createElement(type);
for (const key in props) setProp(el, key, props[key], undefined);
return el;
}
export function createTextInstance(text: string): Text {
return document.createTextNode(text);
}The names say "instance", not "element", and that is deliberate. Whoever calls
this asks the host for "an instance of a button with these props" and never
looks inside what comes back. Here it happens to be an HTMLElement. Text gets
its own function because in the DOM a piece of text is a node as well.
Writing one prop
setProp writes a single prop onto a node. It receives the new value and the
previous one, because writing the new value correctly sometimes means undoing the
old one first. Stripped to one special case, its shape is this:
function setProp(el: HTMLElement, key: string, value: any, prevValue: any): void {
if (key === 'children' || key === 'key' || key === 'ref') return; // React's, not the DOM's
if (key === 'className') {
el.className = value ?? ''; // a property, not an attribute
return;
}
// …one case like this for each prop the DOM treats differently…
if (value == null || value === false) el.removeAttribute(key);
else el.setAttribute(key, value === true ? '' : String(value));
}children, key and ref belong to React; children in particular are other
nodes, and linking them is a separate job. Everything else ends as a plain
attribute: null, undefined and false remove it, true writes it with no
value. In between sits one case per prop the DOM wants written some other way.
The DOM has no single way to set things, and those cases keep that away from
every caller. setProp is not exported. Nobody outside this file sets a single prop.
The real file has five such cases: on… handlers, className, style,
value, and the boolean properties like disabled. The next lessons build on
all of them, so the file gets the full version:
The full setProp
/** Writes ONE prop to the node. `prevValue` is what we wrote last time, if anything. */
function setProp(el: HTMLElement, key: string, value: any, prevValue: any): void {
if (key === 'children' || key === 'key' || key === 'ref') return;
// TEMPORARY SHORTCUT (the "DOM events" lesson replaces it): a real listener on the node itself.
if (key.startsWith('on') && key.length > 2 && key[2] === key[2].toUpperCase()) {
const eventName = key.slice(2).toLowerCase();
if (typeof prevValue === 'function') el.removeEventListener(eventName, prevValue);
if (typeof value === 'function') el.addEventListener(eventName, value);
return;
}
switch (key) {
case 'className':
el.className = value ?? '';
return;
case 'style': {
const style = el.style as any;
if (prevValue) {
for (const k in prevValue) if (!value || !(k in value)) style[k] = '';
}
if (value) {
for (const k in value) {
const v = value[k];
style[k] = typeof v === 'number' && !unitless.has(k) ? `${v}px` : (v ?? '');
}
}
return;
}
case 'value':
// Writing the same value again would move the cursor in a text input.
if ((el as any).value !== String(value ?? '')) (el as any).value = value ?? '';
return;
case 'checked':
case 'selected':
case 'disabled':
case 'hidden':
case 'multiple':
case 'readOnly':
(el as any)[key] = !!value;
return;
}
if (value == null || value === false) el.removeAttribute(key);
else el.setAttribute(key, value === true ? '' : String(value));
}
const unitless = new Set(['opacity', 'zIndex', 'fontWeight', 'lineHeight', 'flex', 'flexGrow', 'flexShrink', 'order']);styleis an object: keys that disappeared are cleared, the rest are written, and numbers getpxunless the property is unitless.value,checked,disabledand friends must be properties, since thevalueattribute is only an input's initial value.valueis only written when it differs, because writing the same value again moves the cursor.
Linking nodes
The file continues with the functions that link nodes together:
export function appendChild(parent: Node, child: Node): void {
parent.appendChild(child);
}
export function insertBefore(parent: Node, child: Node, before: Node): void {
parent.insertBefore(child, before);
}
export function removeChild(parent: Node, child: Node): void {
if (child.parentNode === parent) parent.removeChild(child);
}These are one-liners over DOM methods with the same names. They exist because of
who will call them: code that writes parent.appendChild(...) itself only works
in a browser. The single extra is that removeChild does nothing, instead of
throwing, when the node is not a child of that parent.
What changed?
That covers the first render. For the second one we get the old props and the new props of the same node. Writing every prop again would work, but the DOM is the slow part, so I want the list of keys that actually changed. It needs one helper:
/** True when two objects have the same keys with the same (Object.is) values. */
export function shallowEqual(a: any, b: any): boolean {
if (Object.is(a, b)) return true;
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
const ka = Object.keys(a);
const kb = Object.keys(b);
if (ka.length !== kb.length) return false;
for (const k of ka) {
if (!Object.prototype.hasOwnProperty.call(b, k) || !Object.is(a[k], b[k])) return false;
}
return true;
}The diff itself, and the function that applies it, close src/dom-host.ts:
const isPlainObject = (v: any) => v !== null && typeof v === 'object';
/** Returns the names of the props that changed, or null if nothing changed. */
export function diffProperties(oldProps: any, newProps: any): string[] | null {
const changed: string[] = [];
for (const key in oldProps) {
if (key === 'children') continue;
if (!(key in newProps)) changed.push(key);
}
for (const key in newProps) {
if (key === 'children') continue;
if (Object.is(oldProps[key], newProps[key])) continue;
// style={{...}} is a new object every time: compare its VALUES.
if (key === 'style' && isPlainObject(oldProps.style) && isPlainObject(newProps.style)) {
if (shallowEqual(oldProps.style, newProps.style)) continue;
}
changed.push(key);
}
return changed.length > 0 ? changed : null;
}
export function commitUpdate(el: HTMLElement, changedKeys: string[], oldProps: any, newProps: any): void {
for (const key of changedKeys) setProp(el, key, newProps[key], oldProps[key]);
}The first loop collects keys that disappeared, the second collects keys that are
new or different. style gets special treatment: an inline style={{ … }} is a
new object on every render, so comparing by identity would report it as changed
every time. For style only, the diff looks one level inside.
diffProperties never touches the DOM. It reads two objects and returns strings,
or null for "leave this node alone". commitUpdate is the other half: it
applies that list and nothing more. The split is on purpose. The diff is pure and
can run at any moment; the commit is the only step the user can see.
The demo
The demo plays the reconciler by hand with a single button. Its props are a plain object rebuilt from scratch for every count, and each click diffs the old props against the new ones and commits whatever changed. Step through it:
An element card beside a DOM node, after the fifth click. The element’s props: className 'counter', style { padding: 8, fontWeight: 600 }, title 'hot', disabled true and onClick handleClick. diffProperties(props(4), props(5)) returned ["disabled"], so one prop was written. The node is a button with class="counter", style="padding: 8px; font-weight: 600;", title="hot" and disabled, plus a click listener that calls handleClick.
Step 1 of 4
- The mount.
createInstancegetsprops(0)and sends every prop throughsetProp, one at a time.classNamebecomesclass, the numbers instylegetpx(but notfontWeight), andonClickbecomes a listener, not an attribute.disabled: falseis written too, as a property, so there’s no attribute to see. - Click 1. The button gets a brand-new props object, with a brand-new
styleinside.diffPropertieslooks one level intostyleand finds the same values, andonClickis the same function. The answer isnull: nothing is written and the node isn’t touched. Clicks 2 and 4 look exactly like this. - Click 3.
titlegoes from'cold'to'hot'. That’s the one key the diff returns, socommitUpdatecallssetProponce and only thetitleattribute is rewritten. - Click 5. Now
disabledistrue. The diff returns["disabled"],setPropsets the property and the button switches itself off. Five clicks, two DOM writes.
Highlighted lines: 3 to 9, 12.
Highlighted lines: 19 to 22.
Highlighted lines: 6, 21 to 22.
Highlighted lines: 7, 21 to 22.
import { createInstance, createTextInstance, appendChild, diffProperties, commitUpdate } from './dom-host';
const props = (count: number) => ({
className: 'counter',
style: { padding: 8, fontWeight: 600 }, // a NEW object every time, same values
title: count >= 3 ? 'hot' : 'cold',
disabled: count >= 5,
onClick: handleClick, // the SAME function every time
});
// mount: every prop goes through setProp once
const button = createInstance('button', props(0));
appendChild(button, createTextInstance('Click me'));
appendChild(document.getElementById('root')!, button);
// update: diff old and new props, commit only what changed
let clicks = 0;
function handleClick() {
const oldProps = props(clicks);
const newProps = props(++clicks);
const changed = diffProperties(oldProps, newProps);
if (changed !== null) commitUpdate(button, changed, oldProps, newProps);
console.log(`click ${clicks}:`, JSON.stringify(changed));
}Five clicks print this in the console:
click 1: null
click 2: null
click 3: ["title"]
click 4: null
click 5: ["disabled"]That is the answer to the first question. The button gets a new props object and
a new style object on every click, and the diff still says null: zero DOM
writes. Only the third click, where the title flips, and the fifth, where the
button switches itself off, have anything to commit.
The demo's code
import { createInstance, createTextInstance, appendChild, diffProperties, commitUpdate } from './dom-host';
const props = (count: number) => ({
className: 'counter',
style: { padding: 8, fontWeight: 600 }, // a NEW object every time, same values
title: count >= 3 ? 'hot' : 'cold',
disabled: count >= 5,
onClick: handleClick, // the SAME function every time
});
// mount: every prop goes through setProp once
const button = createInstance('button', props(0));
appendChild(button, createTextInstance('Click me'));
appendChild(document.getElementById('root')!, button);
// update: diff old and new props, commit only what changed
let clicks = 0;
function handleClick() {
const oldProps = props(clicks);
const newProps = props(++clicks);
const changed = diffProperties(oldProps, newProps);
if (changed !== null) commitUpdate(button, changed, oldProps, newProps);
console.log(`click ${clicks}:`, JSON.stringify(changed));
}The page that loads it only needs a #root to mount into:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Lesson demo</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/demo.ts"></script>
</body>
</html>Run it with npx vite from the lesson's folder and open the console.
What we simplified
- Events.
onClickis a directaddEventListener, and the event name is only the prop name in lower case. The later lesson "DOM events" replaces this. - The caller. There is no reconciler yet, so the demo decides by hand when to create, diff and commit.
setPropis trimmed. NodangerouslySetInnerHTML, nodefaultValue, no string styles. They follow the same pattern as the cases shown.
Where this plugs in
Look at the demo once more: it never calls document.createElement and never
sets an attribute. It only calls the host's functions. The reconciler we build in the
coming lessons will keep exactly that discipline. It will never touch the DOM
directly, only this API. That is the answer to the second question: write the
host's functions over native views, a canvas or a terminal, and everything
above them keeps working. That is why other renderers can exist.
Next, the first milestone glues this host to elements and fibers, and a tree appears on the page without me calling a host function by hand.