How it works · small JavaScript library for building screens
How Preact works
The same idea as React, in a few kilobytes: you describe the screen, and Preact changes only what is different.
Think of it like this. A decorator with a list of how the room should look. They walk the room once, comparing each thing to the list, and fix what doesn’t match as they go.
- 📝 Descriptions Every tag you write becomes a small object that says what should be there. src/create-element.js
- 🚪 Render The way in: put this description into that place on the page. src/render.js
- 🔍 The diff Compares the new description with the last one and changes the page where they differ. src/diff
- 🧩 Components Remembers which components asked to be drawn again, and redraws them together. src/component.js
- 🪝 Hooks useState, useEffect and the rest, kept in a separate small package. hooks/src/index.js
Follow one thing through: you press a button that calls setCount(1)
- The hook finds its own slot in the component’s list of hooks, by the order it was called in.hooks/src/index.js
- The component is marked as needing a redraw and added to a queue. Several changes in a row make one redraw.src/component.js
- A moment later the queue is worked through, parents before children.src/component.js
- Your component function runs again and returns a new description.src/diff/index.js
- Its children are matched with the old ones, by key and type, so the same thing keeps the same element.src/diff/children.js
- Only the attributes and text that changed are written to the page.src/diff/props.js
The clever bit: One listener per event, however often you re-render
Your onClick is usually a new function on every render. Adding and removing a browser listener each time would be slow. So Preact attaches one small function per event name to the element, and keeps your handler in a table on the element itself (dom._listeners). A re-render just swaps the entry in the table. The browser’s listener never changes.
Words you’ll meet
- virtual node
- A small object that describes one tag or component.
- diff
- Comparing the new description with the old one to find what changed.
- key
- A name you give a list item so it can be recognised when the list changes.
- hook
- A function like useState that gives a component memory.
Good questions to ask next
- How does Preact know which hook is which?
- What happens when a list is reordered?
- Why is it so much smaller than React?
Open Preact in Bento and ask them there. It reads the project in your browser, draws its parts as a map you can press, and opens the real code behind each one.
Take Preact apart yourself.
Free and open source. Nothing to install, no account.
Ideas inside it
More projects, taken apart
Written by hand from the code as it was on 2026-11-30 (commit 05d9e9b). Preact belongs to its authors; this page is an independent explanation. Spot a mistake? Tell us.