Unreact
LiveBuilding a React-like runtime from scratch, explained through code, tree diagrams, and one counter's journey from state to screen.
- Period
- Oct 2026 — Present
- TypeScript
- DOM
- Bun
A button says Count: 0. You click it. Now it says Count: 1.
In React, that’s a useState call and an event handler. But who remembers the
count after the function returns? Who calls the function again? And how does its
new return value become a change on screen?
I built Unreact to answer those questions. It’s a small React-like runtime in TypeScript, with no React dependency. This walkthrough follows one counter through its implementation: plain objects, DOM nodes, reconciliation, hooks, effects, and context.
The snippets below omit some types and branches for readability. File names point to the implementation in the repository.
1. Describe the UI without creating it
Start with a button:
const button = createElement('button', { id: 'counter' }, 'Count: 0')
In src/lib/index.ts, createElement returns an object. It doesn’t call any
browser APIs:
function createElement(element, props, ...children) {
return { element, props, children }
}
So button is just this:
{
element: 'button',
props: { id: 'counter' },
children: ['Count: 0'],
}
That’s the virtual DOM here: a description of the UI stored in JavaScript. Children can be text, numbers, or more element objects. Nest the objects and you get a tree:
const tree = createElement(
'section',
{},
createElement('h1', {}, 'Counter'),
createElement('button', { id: 'counter' }, 'Count: 0'),
)
Virtual tree
section
├── h1
│ └── "Counter"
└── button { id: "counter" }
└── "Count: 0"
Nothing is on screen yet. That separation is useful: I can build and compare UI descriptions before deciding what to change in the browser.
2. Turn the description into real DOM
The next job is translation. A string becomes a text node. An element object becomes a DOM element. Repeat for its children.
This is the core of createDom, also in src/lib/index.ts:
function createDom(node) {
if (typeof node === 'string' || typeof node === 'number') {
return document.createTextNode(String(node))
}
const element = document.createElement(node.element)
updateProps(element, node.props, {})
for (const child of node.children) {
element.appendChild(createDom(child))
}
return element
}
The recursion follows the same shape as the tree:
Description Browser API
───────────────────────── ─────────────────────────────
{ element: 'section', ... } → document.createElement('section')
├── { element: 'h1', ... } → document.createElement('h1')
│ └── 'Counter' → document.createTextNode('Counter')
└── { element: 'button' } → document.createElement('button')
└── 'Count: 0' → document.createTextNode('Count: 0')
render appends the completed subtree to a container:
function render(node, container) {
container.appendChild(createDom(node))
}
const root = document.getElementById('root')!
render(tree, root)
Now the button exists. But render only appends. Calling it again would add
another tree, not update the first one. For updates, I need a comparison.
3. Compare what was there with what comes next
Imagine the count changes from 0 to 1. The next UI description looks almost
identical:
Previous tree Next tree
section section
├── h1 ├── h1
│ └── "Counter" │ └── "Counter" same
└── button └── button same tag
└── "Count: 0" └── "Count: 1" changed
I don’t need a new section, heading, or button. I need to change the button’s text child.
updateElement in src/lib/index.ts compares one child position at a time. Its
decisions are small enough to draw:
Compare next node with previous node
│
├── No next node? → Remove existing DOM node
├── No previous node? → Create and insert DOM subtree
├── Text involved? → Replace if values differ
├── Different element tag? → Replace DOM subtree
└── Same element tag? → Keep DOM element
Update changed props
Compare children by position
For matching elements, the important part is:
updateProps(element, newNode.props, oldNode.props)
// Remove extra trailing children backwards first.
for (let i = oldNode.children.length - 1; i >= newNode.children.length; i--) {
updateElement(element, null, oldNode.children[i] ?? null, i)
}
for (let i = 0; i < newNode.children.length; i++) {
updateElement(
element,
newNode.children[i] ?? null,
oldNode.children[i] ?? null,
i,
)
}
Why remove backwards? childNodes is live. Removing child 0 shifts the remaining
children left; removing from the end avoids changing positions I still need.
For the counter’s changed text, Unreact uses this branch:
if (isTextNode(newNode) || isTextNode(oldNode)) {
if (newNode !== oldNode) {
parent.replaceChild(createDom(newNode), targetNode)
}
return
}
The button stays. Its old text node is replaced with a new one. This is not an
in-place textContent update, and there’s no separate patch list: Unreact
compares and mutates DOM synchronously as it walks.
Props need their own cleanup
Keeping an element means handling what changed and what disappeared.
updateProps removes missing props, then applies new or changed values.
Prop change DOM work
─────────────────────────── ──────────────────────────────
onClick: oldFn → newFn Remove old listener, attach new
style: { color: 'red' } → {} Clear old style declarations
className: 'active' → absent Remove class attribute
value: 'hello' → 'world' Update input's live value too
Setting attributes alone isn’t enough. An event listener needs its previous
function reference removed. An input has a live value property. These details
are part of making a retained DOM node match its next description.
Position is not identity
My diff has no keyed matching. If I insert an item at the beginning of a list, it compares each new child with whatever used to occupy that position:
Position Previous Next Comparison
0 Alice Zoe Alice → Zoe
1 Bob Alice Bob → Alice
2 — Bob Insert Bob
It can produce the right labels while retaining the wrong conceptual item’s DOM node. That’s why keyed identity matters for lists with focus or local DOM state. This implementation doesn’t solve that problem yet.
4. Give each mounted component somewhere to remember things
A function can calculate the next tree:
function Counter(count: number) {
return createElement('button', {}, `Count: ${count}`)
}
But the function itself doesn’t remember its previous call. Something outside it must store the old tree and know where to render the new one.
In src/lib/component.ts, a WeakMap associates each container with a persistent
component record:
componentRegistry (WeakMap)
└── root DOM container
└── component record
├── component Function to call
├── node Previous virtual tree
├── hooks Persistent hook slots
├── contextValues Supplied context values
├── pendingEffects Work queued during render
└── rerender Render into this container again
renderComponent selects that record before calling the function, then compares
its return value with the saved tree:
setCurrentComponentContext(context)
try {
newNode = component()
} finally {
setCurrentComponentContext(null)
}
updateElement(container, newNode, context.node)
context.node = newNode
On the first render, context.node is null, so the diff inserts the tree. On
later renders, the same path updates it. The finally also clears the active
record if the component throws.
Now there’s a place for state to survive between calls.
5. Hooks are slots, not local variables
Here’s the counter with its own state:
function Counter() {
const [count, setCount] = useState(0)
return createElement(
'button',
{ onClick: () => setCount((n) => n + 1) },
`Count: ${count}`,
)
}
renderComponent(Counter, root)
useState in src/lib/hooks.ts reads an array slot from the active component
record. A hook index starts at zero each render and advances on every
useState or useEffect call.
const component = currentComponent
const index = hookIndex++
if (!(index in component.hooks)) {
component.hooks[index] = initialValue
}
const value = component.hooks[index]
With two state calls, memory looks like this:
Component code Persistent hooks array
───────────────────────────────────── ──────────────────────
useState(0) // first call → [0] 0
useState('Loki') // second call → [1] 'Loki'
Next render: index returns to 0. Array stays.
There is no lookup by variable name. The first call gets slot 0, the second
gets slot 1. Put a hook behind a condition and later calls can read the wrong
slots. The hook-order rule follows directly from this storage model.
The setter captures both the component record and its slot:
const setState = (action) => {
const previous = component.hooks[index]
const next = typeof action === 'function' ? action(previous) : action
if (Object.is(previous, next)) return
component.hooks[index] = next
component.rerender()
}
By click time, currentComponent is no longer set. The captured record is what
lets the setter find the right state anyway. Reading the slot when the setter
runs also gives a functional updater the latest stored value.
One click, end to end
Click button
│
▼
setCount(n => n + 1)
│
├── Read hooks[0]: 0
├── Store hooks[0]: 1
└── Call component.rerender()
│
▼
Reset hook index to 0
Call Counter()
useState reads 1
│
▼
New tree: button → "Count: 1"
│
▼
Compare with saved tree
Keep button; replace text node
│
▼
Save new tree
That’s the complete state-to-DOM loop. Each setter that changes state renders synchronously; this runtime doesn’t batch updates or schedule work like React.
6. Effects run after the DOM update
Some work isn’t a UI description. Updating the document title, for example:
useEffect(() => {
document.title = `Count: ${count}`
}, [count])
useEffect also uses a hook slot, but stores dependencies and an optional cleanup
function instead of a state value. During rendering, it compares dependencies
with Object.is and queues work when they change.
During component call After DOM update
───────────────────────── ─────────────────────────────
Read previous dependencies Run previous cleanup, if any
Compare with next values Save next effect state
Queue effect if changed Call effect
Keep returned cleanup
At the end of renderComponent, the ordering is:
updateElement(container, newNode, context.node)
context.node = newNode
const pendingEffects = context.pendingEffects.splice(0)
pendingEffects.forEach((effect) => effect())
Saving the tree before running effects matters: an effect can trigger another state update. That render needs the latest tree as its starting point. Taking the callbacks out of the queue first keeps them separate from newly queued work.
These effects run synchronously after DOM mutation—not necessarily after the browser paints. Previous cleanup runs before an effect reruns, but cleanup on unmount is still unfinished. This isn’t React’s full effect lifecycle.
7. Context is a scoped lookup
State belongs to a component record. Context supplies values that a component can read without receiving them as individual arguments.
In src/lib/context.ts, a context has a unique symbol and a default:
function createContext(defaultValue) {
return {
id: Symbol('context'),
defaultValue,
}
}
A scope is a map keyed by those symbols. Supplying a value copies the parent scope and overrides one entry:
const childValues = new Map(parentValues)
childValues.set(context.id, value)
Parent scope Copied child scope
Theme → 'light' Theme → 'dark' overridden
Locale → 'en' Locale → 'en' inherited
Parent map remains unchanged.
useContext checks the component record’s scope. If the symbol isn’t present,
it returns the context’s default.
const ThemeContext = createContext<'light' | 'dark'>('light')
function ThemeLabel() {
const theme = useContext(ThemeContext)
return createElement('p', {}, `Theme: ${theme}`)
}
const scope = createProviderValues(new Map(), ThemeContext, 'dark')
renderComponent(ThemeLabel, root, scope)
The paragraph says Theme: dark. Without the supplied scope, it says Theme: light.
For now, scopes are passed explicitly at the root. There are no nested provider nodes or nested component instances carrying values down a component tree. The map-copying mechanism exists; that tree integration doesn’t yet.
How the codebase fits together
Each file answers a different part of the original question:
src/lib/
├── types.ts What do nodes and component records contain?
├── index.ts How do descriptions become DOM and get updated?
├── component.ts Who owns render history and calls the function again?
├── hooks.ts Where do state and effect memory live?
├── context.ts How are scoped values created?
├── guards.ts Which kind of node or prop are we handling?
└── utils.ts How does an event prop map to an event name?
The runtime flow connects them:
renderComponent component.ts
│
├── Select component record
├── Run component
│ ├── Read state / context hooks.ts
│ ├── Queue effects hooks.ts
│ └── Return element objects index.ts: createElement
│
├── Compare old and new trees index.ts: updateElement
│ └── Create / remove / update DOM
│
├── Save new tree
└── Run queued effects
What building it made clear
UI = f(state) describes the component’s job. The runtime supplies the memory
and DOM work that let the function keep doing that job:
- Element objects describe the desired UI without creating it.
- Reconciliation compares descriptions while retaining matching DOM elements.
- Component records preserve render history and hook slots between calls.
- State setters change that memory and request another render.
- Effects queue work for after the DOM update.
- Context scopes supply values without mutating one shared global value.
A virtual tree isn’t automatically faster than direct DOM updates. Maintaining and comparing descriptions adds work too. For this project, its value is making updates declarative: the component describes what it wants, and the runtime handles the transition.
Unreact is a learning project, not a React-compatible replacement. It has no keyed reconciliation, Fiber scheduler, JSX runtime, nested component tree, or complete unmount lifecycle. Those boundaries are useful: I can follow one click through the entire implementation without hiding the mechanism behind another framework.