Render and hydrate
Render HTML with renderToString and activate it with mount.
A component returns JSX. You turn that into HTML on the server and into a live tree in the browser.
| API | Env | Output |
|---|---|---|
await renderToString(component) |
Server | HTML plus snapshot wrap |
await renderToString(component, { markers: false }) |
Server | Inner HTML only |
mount(el, component) |
Client | Live tree |
mount(el, component, { hydrate: true }) |
Client | Hydrate existing HTML |
Return a view
Prefer JSX. Strings become text nodes.
const const A: () => ViewA = () => <JSX.IntrinsicElements.p: HTMLAttributes<HTMLParagraphElement>p>Hello</JSX.IntrinsicElements.p: HTMLAttributes<HTMLParagraphElement>p>;
const const B: () => stringB = () => "hello";
Server render
import { const atom: AtomFnatom, const renderToString: (fn: Component, opts?: RenderToStringOptions) => Promise<string>renderToString } from "ilha";
const const Counter: () => ViewCounter = () => {
const const count: AtomHandle<number, number>count = atom<number>(init: number | Atom<number>, options?: AtomOptions<number> | undefined): AtomHandle<number, number> (+2 overloads)An existing Effect atom, or a plain value. Store a function with
`atom.lazy(() => fn)`; the `ilha/oxlint` rule `function-in-atom` flags
`atom(fn)`.atom(0);
return <JSX.IntrinsicElements.p: HTMLAttributes<HTMLParagraphElement>p>{const count: AtomHandle<number, number>count}</JSX.IntrinsicElements.p: HTMLAttributes<HTMLParagraphElement>p>;
};
const const html: stringhtml = await function renderToString(fn: Component, opts?: RenderToStringOptions): Promise<string>renderToString(const Counter: () => ViewCounter);
Default output looks like:
<div data-ilha data-ilha-state='{"v":[0]}'>
<p>0</p>
</div>
| Option | Default | Meaning |
|---|---|---|
snapshot |
true |
Embed atom values for hydration |
markers |
true |
Wrap in <div data-ilha> |
timeout |
none | Serialize after this many ms even if busy |
Pass { markers: false } when a host already exists. With both markers: false and snapshot: false, the output can never hydrate, so renderToString also drops the hole hosts (<span data-ilha-slot>) and emits plain markup.
renderToString builds HTML without a DOM. It runs in Node, Bun, and edge runtimes with no polyfill.
Mount
import { const mount: (el: Element, fn: Component, opts?: MountOptions) => (() => void)mount } from "ilha";
const const App: () => ViewApp = () => <JSX.IntrinsicElements.p: HTMLAttributes<HTMLParagraphElement>p>Hello</JSX.IntrinsicElements.p: HTMLAttributes<HTMLParagraphElement>p>;
const const root: HTMLElement | nullroot = var document: Document**`window.document`** returns a reference to the document contained in the window.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/document)document.Document.getElementById(elementId: string): HTMLElement | nullThe **`getElementById()`** method of the Document interface returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.getElementById("app");
if (const root: HTMLElement | nullroot) {
const const unmount: () => voidunmount = function mount(el: Element, fn: Component, opts?: MountOptions): (() => void)mount(const root: HTMLElementroot, const App: () => ViewApp);
}
Hydrate
If the host contains [data-ilha] markup from renderToString, pass hydrate: true:
import { const mount: (el: Element, fn: Component, opts?: MountOptions) => (() => void)mount } from "ilha";
const const App: () => ViewApp = () => <JSX.IntrinsicElements.p: HTMLAttributes<HTMLParagraphElement>p>Hello</JSX.IntrinsicElements.p: HTMLAttributes<HTMLParagraphElement>p>;
const const root: Element | nullroot = var document: Document**`window.document`** returns a reference to the document contained in the window.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/document)document.ParentNode.querySelector<Element>(selectors: string): Element | null (+4 overloads)Returns the first element that is a descendant of node that matches selectors.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/querySelector)querySelector("[data-ilha]");
if (const root: Element | nullroot) function mount(el: Element, fn: Component, opts?: MountOptions): (() => void)mount(const root: Elementroot, const App: () => ViewApp, { MountOptions.hydrate?: boolean | undefinedhydrate: true });
Hydration restores atom snapshots in declaration order, then attaches events. Your component can return an element, a component, or a Fragment at the root. Ilha morphs the first client render into the server markup, so the nodes stay in place and keep what a user typed before hydration. An element root whose tag differs from the server markup logs a warning and does a full mount.
Wait for a rerender
mount() returns unmount. To learn when the DOM reflects an update, pass onIdle. It runs after the first paint and again each time pending rerenders, async components, and watchers settle:
function mount(el: Element, fn: Component, opts?: MountOptions): (() => void)mount(const root: HTMLElementroot, const App: () => ViewApp, {
MountOptions.onIdle?: (() => void) | undefinedCalled each time the mount has no pending work left: after the first
paint and again after every rerender, async component, and watcher
settles. Use it to learn when the DOM reflects an atom update.onIdle: () => {
var console: ConsoleThe `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```console.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.log("DOM is up to date");
},
});
Atom updates rerender in a microtask, so the DOM changes right after the set() call returns, not during it.
Wrap a vanilla library
Some libraries own their DOM node: maps, editors, charts. You grab the node with ref, build the instance on mount, and destroy it on the null call:
declare const const createMap: (el: HTMLDivElement) => {
destroy: () => void;
}
createMap: (el: HTMLDivElementel: HTMLDivElement) => { destroy: () => voiddestroy: () => void };
const const MapView: () => ViewMapView = () => {
let let map: {
destroy: () => void;
} | null
map: { destroy: () => voiddestroy: () => void } | null = null;
return (
<JSX.IntrinsicElements.div: HTMLAttributes<HTMLDivElement>div
class?: Attrclass="map"
ref?: ((el: (HTMLDivElement & Element) | null) => void) | undefinedref={(el: (HTMLDivElement & Element) | nullel) => {
if (el: (HTMLDivElement & Element) | nullel) {
let map: {
destroy: () => void;
} | null
map = const createMap: (el: HTMLDivElement) => {
destroy: () => void;
}
createMap(el: HTMLDivElement & Elementel);
} else {
let map: {
destroy: () => void;
} | null
map?.destroy: () => voiddestroy();
let map: {
destroy: () => void;
} | null
map = null;
}
}}
/>
);
};
Each rerender calls the previous ref with null, then the new ref with the element in the document, so always route teardown through the null branch. If code outside a ref fills an element’s children, mark the element with data-morph-preserve="children" so rerenders leave that content alone. See Keep user state across rerenders.
Before you mount a second tree on the same host, call the first unmount():
let let unmount: () => voidunmount = function mount(el: Element, fn: Component, opts?: MountOptions): (() => void)mount(const root: HTMLElementroot, const App: () => stringApp);
let unmount: () => voidunmount();
let unmount: () => voidunmount = function mount(el: Element, fn: Component, opts?: MountOptions): (() => void)mount(const root: HTMLElementroot, const App: () => stringApp);
Skipping the first unmount() leaves two trees — and two ref callbacks — fighting over one node.
File routes
@ilha/void and @ilha/astro call renderToString and mount for you. See Void and Astro.