Learning on Web Dev Open is free for all.

Framework Internals > Two hundred lines of frameworkA virtual DOM is an embarrassingly plain object
Phase 04Two hundred lines of framework185 of 434

A virtual DOM is an embarrassingly plain object

Type, props, children. That is the whole data structure, and JSX is a function call that builds it.

Concept13 minAI pair

{ type: "div", props: { className: "card", children: [...] } }. That is an element. If type is a string it names a host element; if it is a function it names a component, and rendering it means calling it and recursing into what it returns. There is no cleverness in the data structure at all, which is the point: it is cheap to create and cheap to throw away.

JSX is syntax for exactly that call. <Card title="x">hi</Card> becomes jsx(Card, { title: "x", children: "hi" }). Understanding this makes several mysteries evaporate at once: why components must be capitalised, why children is just another prop, why you can pass a component as a value, and why key is pulled out separately rather than living in props.

The word "virtual" oversells it. The tree is not a shadow copy of the DOM; it is a description of what the DOM should be, produced fresh each render and immediately compared against the last one. It is faster than the DOM not because objects are magic but because you can create ten thousand of them without triggering a single style recalculation.

You should now be able to

  • Describe the shape of an element node
  • Explain what JSX compiles to
Ask the community

Loading…