Preact
Preact 11 components, rendered on the server with preact-render-to-string
and hydrated with Preact’s hydrate, which adopts the server’s nodes. The
droplet below is a Preact component served by the demo server: its load sets
the start, Preact renders it to HTML, and the button works once the bundle
hydrates it.
counter · Preact
Server HTML: the button works once Preact hydrates.
/** @jsxImportSource preact */import { useEffect, useState } from "preact/hooks";import type { DropletProps } from "./$types";
export const ssr = true;export const hydrate = true;
export default function Counter({ data }: DropletProps) { // What the server load returned. Always the value: Preact has no // use(promise), so the renderer waits for it before rendering. const { framework, start } = data; const [added, setAdded] = useState(0); // False in the server's HTML; true once this component runs in the browser. const [hydrated, setHydrated] = useState(false); useEffect(() => setHydrated(true), []);
return ( <section class="demo-card" data-hydrated={String(hydrated)}> <p class="demo-row"> <span class="demo-tag">counter · {framework}</span> </p> <p class="demo-row"> <output class="demo-title" aria-live="polite"> {start + added} </output> <button type="button" class="demo-button" onClick={() => setAdded((n) => n + 1)}> Add one </button> </p> <p class="demo-muted"> {hydrated ? `Hydrated: ${framework} runs the button in this tab.` : `Server HTML: the button works once ${framework} hydrates.`} </p> </section> );}import type { LoadEvent } from "./$types";
/** * Runs on the server only. The count starts where the server says, and the * name of the framework comes with it. The same for everyone, so a browser * (or a cache in front) may keep it for five minutes. */export const load = ({ setHeaders }: LoadEvent) => { setHeaders({ "cache-control": "public, max-age=300" }); return { framework: "Preact", start: 3 };};Add it to a project
Section titled “Add it to a project”npx djs add counter --framework preactIt installs what the project lacks and adds preact() to renderers invite.config.ts, asking first, then writes src/droplets/counter/+droplet.tsx.
As the project's first .tsx framework, it also sets"jsx": "react-jsx", "jsxImportSource": "preact" in tsconfig.json.
Every step it takes is in Add a renderer. What it installs for Preact:
| Package | Installed as |
|---|---|
@dropletsjs/renderer-preact | a dev dependency, at exactly the version of @dropletsjs/droplets you have |
preact@^11.0.0 | a dependency |
preact-render-to-string@^6.8.0 | a dependency |
By hand:
npm install preact preact-render-to-stringnpm install -D @dropletsjs/renderer-preactthen import { preact } from "@dropletsjs/renderer-preact" and preact() in renderers.
The files
Section titled “The files”| File | What it is |
|---|---|
+droplet.tsx, +droplet.jsx |
The component, the file’s default export. Its flags are named exports of this file. |
+error.tsx, +error.jsx |
The error page, optional. It follows the droplet’s flags. |
+droplet.ts, +droplet.server.ts |
The loads, as for every framework: Writing droplets. |
The flags are literal export const declarations of the component file. A
flag exported from +droplet.ts or +droplet.server.ts is ignored.
Which .tsx files are Preact’s. When Preact is the only .tsx
framework in renderers, all of them. Next to React, Solid or Hono JSX, a droplet file is
Preact’s when it imports preact, preact-render-to-string or @dropletsjs/renderer-preact, a subpath included (preact/hooks), or carries a /** @jsxImportSource preact */
comment (djs add writes one at the top of every Preact component), and
names no other .tsx framework. A name such as +droplet.preact.tsx would not help: it still ends in .tsx. See
Which renderer a .tsx file belongs to.
import { useState } from "preact/hooks";import type { DropletProps } from "./$types";
export const hydrate = true;
export default function Hello({ data, children }: DropletProps) { const [clicks, setClicks] = useState(0); // Always the value: the renderer awaits a promise of it before rendering. return ( <> <h1>{data.greeting}</h1> <button onClick={() => setClicks((n) => n + 1)}>{clicks}</button> {children} </> );}/** @jsxImportSource preact */import type { DropletErrorProps } from "./$types";import "./error.css";
export default function HelloError({ error, children }: DropletErrorProps) { return ( <> <p class="oops">{error.message}</p> {children} </> );}error is what handleError in +droplet.server.ts (or +droplet.ts)
returned; see Errors.
What it supports
Section titled “What it supports”| Server rendering | yes: ssr = true, the default; ssr = false mounts it in the browser only (render) |
hydrate |
true (the default), "visible", "interactive", false |
| Prerendering | yes: prerender = true, once per event entries returns: Prerendering |
| Forms | useEnhanceDropletForm(formRef, options?) of @dropletsjs/renderer-preact/form |
Two mistakes fail vite build, and vite dev as well, with a message that
names the fix:
-
a
.tsxdroplet that names no framework, or two, when several share the extension. Withreact()andpreact()inrenderers:droplets: counter/+droplet.tsx: react and preact both handle this file and it imports neither; import from react or preact, or add a /** @jsxImportSource <package> */ commentThe message lists every renderer that shares the extension, in the order of
renderers. -
importing React, which nothing aliases to
preact/compat, or any other configured framework, even through a neutral file:droplets: a preact droplet imports react code: src/droplets/counter/+droplet.tsx -> src/lib/react-label.ts -> react/index.js. A droplet uses its own framework's modules and neutral code only.
Other mistakes are ignored, with a warning:
-
a flag that is not a literal, such as
export const hydrate = isMobile, warns undervite devandvite build, and the flag keeps its default:[droplets:framework] `export const hydrate` must be true, false, "visible" or "interactive"; ignoring it { droplet: 'counter', found: 'isMobile' } -
an
+error.tsxthat names another framework is not used; undervite devandvite buildwarn oncecounter/+error.tsx is not a preact component like the droplet; ignored, the error page is written in the droplet's framework.
Specifics
Section titled “Specifics”- Data is always the value. Preact has no
use(promise): when the element mounts a droplet from scratch (client-only, remounted in dev), the renderer awaits itsdatafirst, then renders. When the data rejects,+error.tsxrenders in its place with whathandleErrorreturned, and nothing renders whenhandleErrorrejects too. A droplet mounted this way with an error page also renders inside the renderer’s error boundary, which shows+error.tsxfor a render error later on. - Rendering is synchronous.
hydratereturns with the droplet live;mountdoes too once the data is there. - JSX: the renderer compiles its modules with Preact’s automatic runtime
(
preact/jsx-runtime) itself, without@preact/preset-vite. Next to another.tsxframework it compiles only the modules Preact droplets reach. Nothing aliasesreacttopreact/compat, so React droplets in the same project keep React. Attributes are HTML’s:class,for. - Children:
childrenrenders the host’s content, in+droplet.tsxand in+error.tsx. - Styles: imported CSS goes to the droplet’s stylesheet, the error page’s included: Preact components carry no inline styles, and the element links that stylesheet whenever the droplet is on the page.
- Forms: keep the action’s URL from the first render,
const [add] = useState(() => actionUrl("add"))withactionUrlof$droplets/form, then<form method="post" action={add}>.useEnhanceDropletForm(formRef, { action: "add" })sends it withfetchand shows the result in place; withoutonResult, it callsresult.update(). See Actions. - Hot updates: Prefresh, under
vite devwithdev.strategy: "hmr"(the default), on any page that loadsindex.jsfrom the dev server. An edit to a component keeps its hook state. The renderer compiles Prefresh into Preact’s modules only, in its own transform, so nothing of it reaches a React or Solid module next to it. When Prefresh’s runtime does not resolve, the renderer warns and Preact droplets remount on an edit. An edit to the load brings newdatato the live component, its state kept. See Hot updates. - Options:
preact({ plugin: false })leaves compiling to you: both builds then need Preact’s automatic runtime,jsxImportSource: "preact".
The example
Section titled “The example”examples/frameworks/preact
has one droplet per mode, client (ssr = false), ssr-hydrate (with
+error.tsx) and ssr-nohydrate (hydrate = false), with loads, a props
schema, /api endpoints, env variables and a handle hook. Its droplets
render in <djs-preact>. From a clone of the repository:
pnpm install && pnpm buildpnpm --filter @dropletsjs/example-preact dev # http://localhost:5173: the devtools pagepnpm --filter @dropletsjs/example-preact build then start serves it on
http://localhost:8000; /droplets/ssr-hydrate?who=Ana is the fragment a
host pastes into its page.