How Preact works: Components and the render() function
mainPreact builds user interfaces by assembling trees of components and elements.
- Components: Functions or classes that return a description of the UI tree. These descriptions are typically written using JSX or HTM.
- render(vnode, container): This function accepts a tree description (vnode) and creates the corresponding DOM structure inside the provided
container. - Efficient Updates: Subsequent calls to
render()with a new tree will reuse the existing structure and update it in-place. Preact calculates the difference (diffing) between the new and old structures to perform the minimum number of DOM operations required.
import { h, render } from 'preact';
/** @jsx h */
// Initial render
render(
<main>
<h1>Hello</h1>
</main>,
document.body
);
// Update the tree in-place
render(
<main>
<h1>Hello World!</h1>
</main>,
document.body
);