brust 2.0.0-alpha.66
Guide / Rendering tiers

Rendering tiers

The compiler reads each component and picks the cheapest output that still behaves the same. You never pick it; you can always see what it picked.

Three tiers

TierWhenThe browser gets
staticNo hooks, no handlers, no refs. Props in, markup out.HTML only. No JavaScript.
nativeOnly the supported hooks, and event handlers.HTML, plus a small React-free chunk: signals bound to the server's markup.
reactEverything else: context, useTransition, useDeferredValue, Suspense, a component from a package, browser globals read during render.HTML rendered by React on the server, then a React island hydrates it.

The tier is decided per component, bottom-up. A React child inside a native parent becomes an island and the parent stays native, so one island never turns the whole page into React. A page made only of static components gets no <script> tag at all.

It is also decided per call site. A component without state used by a page that has none either (say a List that maps the page’s loader data to a Hero per row) is compiled once for every caller, and a caller could pass values that change, so on its own it may need the runtime for its rows, or React for a value it derives from a prop. Where a call site passes only fixed values (the page’s loader data, literals, the rows of a list that never changes on the client), brust makes a copy of the component for that call site with every prop fixed, and that copy renders static: plain HTML, no script. The same component used from a component with state keeps its own tier. Nothing to write: the compiler proves it from the call site.

The three, live

These are the landing page's three demo components. The tier and the shipped chunk under each one come from this build's manifest, read by the page's loader.

PokemonCardtier static · client none
Bulbasaur#001

Bulbasaur

grasspoison
Charmander#004

Charmander

fire
Squirtle#007

Squirtle

water
CatchCardtier native · client client/catchCard_2b1c6e39-cb01fcbe3b.js
Pikachu
#025

Pikachu

electric
Signalsno re-render
  1. Use the switch or the button.
PokemonSearchtier react · client client/react-pokemonSearch_d9a2c844-3d2aa55133.js
  • #001Bulbasaur
  • #002Ivysaur
  • #003Venusaur
  • #004Charmander
  • #005Charmeleon
  • #006Charizard
  • #007Squirtle
  • #008Wartortle

What decides the tier

You useTier
Props only, or useIdstatic
useState, useMemo, useCallback, useEffect, useLayoutEffect, useRef, useId, useReducer (a state cell and one stable dispatch; the reducer must be a pure function, written inline or in the same module), memo(), event handlers, useStore, and a custom hook whose body uses only these, in the same module or an imported one (the compiler inlines it)native
useContext, useDeferredValue, useTransition, useSyncExternalStore, use(promise), cloneElement, forwardRef and other HOCs, spread props, lazyreact

In a native component, effect dependency arrays are not needed: signals track what an effect reads. A missing dependency still prints effect-deps as a warning, and the tier stays native.

Note

Falling back to React is never a build failure, and that includes passing a function or a changing value to a React child (island-prop): the component that passes it renders with React. Some things are: server-only code reachable from the browser (server-only-in-client), and a list without keys (list-key).

A small function you declare in the component and call in the markup does not cost the tier: for const label = (n: number) => n + ' items', the call {label(count)} is compiled as the expression itself. This holds for an arrow whose body is one expression, called with arguments that contain no call. An arrow with a block body, or one that calls a method of an imported object, stays a function, and a value computed per request from it makes the component a React island (client-function-in-job).

Module-level code. The code brust compiles for a component copies the declarations of its module that it reads, not code that runs when the module loads. So a component that reads a value of its own module, or an import, keeps its tier only when that module provably runs nothing at load; otherwise it is a React island and the build says module-side-effect, naming the declaration and its line. Accepted at module scope: imports, types, functions and arrows that change no module value, and consts built from literals, other accepted constants, functions, template strings and operators, regex literals (without the g or y flag), Array.from({ length: 24 }, (_, i) => `${i}:00`) (a callback that builds a string or number), package calls, and reads of a table another module of your app exports: { icon: ICON.overview } is accepted when ICON is export const ICON = { … } (an object or array literal, also through a re-export) with no getter, spread or computed key on the way to the value, and nothing changes it. A value read that way is not converted to a string or a number at load (`${ICON.overview}` is not accepted). Not accepted: a class, a let or var a function changes, a statement that runs at load, a call of your own function at load, a const read before it is declared. A function changes a module value when it assigns one, or calls push, sort, delete and the like on an object the module may own (a module constant, what a function of the module returns, or a value brust cannot name, such as the result of (c ? a : b)(…)); the same call on the result of an imported function (api(id).delete(id)) does not.

The server runs the precomputed values of a component (a class built by a helper, a useId) for the route's page and layouts and for the components placed directly in them. A component with such a value placed inside another component that has one too is out of that reach. The outer component keeps its tier: at that place the inner one renders as a React island, a copy of it compiled for this purpose, and the build says so with a nested-fed-child warning on the inner component. Everywhere else the inner component keeps its own tier. Before 2.0.0-alpha.53 the outer component became the island (nested-instance), which it still does when the copy would not help, for example when the inner component is given a function.

A precomputed value travels from the worker to the server as JSON. JSON has no NaN, Infinity or bigint, so the worker marks those values and the server reads them back as what they were: a top-level value of a job, and each item of a top-level array, keeps its meaning in text, in an attribute, in a condition and in arithmetic. NaN, Infinity, -Infinity and 10n print as JavaScript prints them, NaN and 0n are false in a test, Infinity is true. A value nested deeper (a member of an object) is not marked: a NaN there arrives as null, and a bigint arrives as its decimal digits. A bigint in loader data is not converted: the page answers 500.

Under brust dev, a job that returns an object, a Date, a Map, a Set or a Promise for a position that prints it (text or an attribute) gets a warning naming the component and the value: React prints those differently from the JSON image brust has. Production prints the same bytes and says nothing.

A React island with per-row props in nested lists, or in the rows of a component inlined into its callers, cannot be server-rendered row by row, so the component around it becomes one React island (nested-instance). Two cases cannot do that: a component that renders itself (a tree, compiled to one template macro) and one that holds a <Dynamic> slot (React cannot render it). There the island is client-only instead: the page prints its host with that row's props and nothing inside, the browser mounts it, the component keeps its tier, and the build says so with an island-client-only warning.

What the template prints, and what runs as a job

The compiler prints an expression into the page’s template when it is in a small subset. It does not translate anything else: an expression outside the subset runs as your own JavaScript, in a server job, so its meaning cannot change. The price is a worker call: the jobs of a page go to the worker together (jobs in dist/manifest.json). A value that needs the browser, or a function, makes the component render with React instead.

The template prints these, with no job:

  • member reads and indexes with a literal key (user.name, items[0]);
  • !, unary -, every binary operator (arithmetic, comparison, &&, ||, ??) and ?:;
  • template strings, and array and object literals;
  • Object.keys(x), Object.entries(x), Object.assign({}, a, b) (which is what an object spread reads as) and Array.from({ length: 3 }), where the length is a literal number from 0 to 1024;
  • ['a', 'b'].includes(x) on an array of literals with at most 16 members;
  • these methods, with literal arguments only: toUpperCase, toLowerCase, trim, slice, startsWith, endsWith, includes and join (the separator is a string literal).

The arguments of those methods must be literals. s.slice(0, 3) and xs.join(', ') are printed by the template; s.slice(0, n) and xs.join(sep), with a name or any other expression as an argument, are not, and the call runs as a job.

These run as a job instead, because they are outside the subset: n.toLocaleString(), n.toPrecision(3), s.padStart(6, '*'), s.trimEnd() and new Date(x).toISOString(). The output is the same as React’s; the page costs a worker call.

How this is checked: in CI, the HTML the server prints for every native and static row of the compiler’s battery is compared with React’s renderToString of the same source and props. A difference fails the build unless a list of known differences explains it.

What the browser loads

A native component or an island needs a small piece of JavaScript in the browser. It is not one file. The runtime is a core (signals, mount, the directive registry) plus feature modules, and a page loads the core and only the features its components use:

  • basics: x-text, x-show, x-ref, and the x-bind-* and x-on-* directives; nearly every native page needs it.
  • if, for, model, html: conditionals, lists, form models and raw HTML, each only for pages that use it.
  • island: the glue that hydrates React islands, only for pages that have one.
  • store: the shared store, only for pages whose components read one.

The build works out the set for each component and the server links the modules of a route, preloaded in the page head. A static page with no island loads none of it. If a template uses a directive that no feature binds, the build stops with runtime-feature-missing instead of shipping a page that does nothing. Before, every page with a native component loaded the whole runtime (about 6 KB gzipped).

Only the components the page drew

Each native component has its own chunk. A response carries the chunk of a native component only when the page it sends contains that component: the server looks for the component’s element in the finished HTML before it writes the script tags. A page whose loader picks one widget out of six loads the chunk of that one. Markup the browser may still show later is part of the HTML too, so its chunks stay: the other branch of a condition over state or over a prop that can change, and the row of a list that is empty on the server (it is sent as a hidden template). A client-side navigation loads the chunks the next page lists before it swaps the page in.

A chunk is always sent, as before, when it bundles an app module that runs code when it loads (a statement at the top level, a class, a constructor other than the ones below, a call that may run code the build cannot follow), so that code runs on every page of the route, as it would in React. A module that only builds its own values when it loads does not count: new Set(…) and new Map(…) of an array literal or of another such value, a spread of one ([...BASE, x]), filter, map, flatMap, reduce and the other array methods with an inline callback on such a value, a call of a function of the same module whose body only builds values, and a template of a string or number const imported from your own module. Plain data is one idea: an export const of one of your modules whose value is a literal of strings, numbers, booleans, null, arrays and plain objects (no function, no computed key, no spread), and which every module of the app only reads. Reading means THEME.page.maxW, ROWS[0].label, ROWS.length, 'named' in row, a spread of it into an array or object literal, for…of over it, and a built-in method that takes no function (find, filter, map, some, join, split,startsWith, padStart, replace with two strings and the like) with the result only read the same way. Anything else makes it not data for every module: an assignment into it,sort or push on it, handing it or one of its objects to a function, returning it or one of its objects, storing one in another value ({ list: ROWS }, const first = ROWS[0]),import() of its module, a import * as ns object used other than as ns.name. A number or a string taken out of it may go anywhere. With plain data, reading it, spreading or copying the numbers and strings, arithmetic on it, KEYS[key] and { [key]: value } with a plain key, and the string, number and array methods above build values too. Built-in prototypes are assumed unpatched. An imported value brust cannot read as plain data (a function result, an object that is not a literal) keeps the chunk. A function the module declares runs nothing until it is called and does not count, but handing one to a package call at load does (the package may run it then). Code outside the app root and its [build] source_roots (packages) is not checked: such a module imported only by components a page does not draw is not loaded on that page, and a package call your module makes at load with data only runs only on pages that carry the chunk. React islands, the runtime and its feature modules are linked as before. [build] component_scripts = "route" in brust.toml sends every chunk the route can draw, as earlier versions did (see Configuration).

Note

Before an island hydrates, its server HTML is visible but not interactive. The island hydrates once its chunk has loaded and the browser is idle (waiting at most 250 ms for an idle moment). A click on an island's server HTML in that window is dropped, not replayed; the same control works on the next click. A React server-rendered page behaves the same way, because React attaches no listeners before hydrateRoot. On a slow connection the window is longer: in our measurements (slow 4G, a 4x slower CPU) it was about half a second, and with no throttling about 20 ms.

When an island is ready

data-hydrated="1" on a <brust-island> means its hydrate call has run, not that React has finished: hydrateRoot and createRoot().render() only schedule the render. Once the island's root has committed (its layout effects have run, its event handlers work), the host gets data-committed="1" and dispatches a brust:island event that bubbles, with detail: { id, phase: 'committed' }. id is the host's data-id. It fires once per host, for hydrated islands and client_only ones alike, after data-hydrated, and never for a host that left the page first.

The signal covers the island's root, not every <Suspense> boundary inside it: React may hydrate the content of an inner boundary after the root commits, and that later hydration sends no event.

Code that may run after the event checks the attribute first:

function ready(island: Element, run: () => void) {
  // committed before this code ran: the attribute says so, the event will not come again
  if (island.getAttribute('data-committed') === '1') return run()
  island.addEventListener('brust:island', run, { once: true })
}

document.addEventListener('brust:island', (e) => {
  const { id, phase } = (e as CustomEvent<{ id: string; phase: 'committed' }>).detail
  console.log(id, phase, e.target) // e.target is the <brust-island> host
})

See what you got

Every fallback is printed once per component by the build, with the rule and the line. This is the pokedex example's build:

~/pokedex
$ bun run build
warning hook-unsupported components/TeamBuilder.tsx:12:3 hook useTransition is not supported
warning hook-unsupported components/UnifiedIsland.tsx:11:3 hook useTransition is not supported
[brust] built dist in 73ms

The full answer is in dist/manifest.json: each component has a tier, the client chunk it ships (null when nothing ships) and its server jobs.

dist/manifest.json
"pokemonSearch_<hash>": {
  "tier": "react",
  "client": "client/react-pokemonSearch_<hash>-<hash>.js",
  "jobs": [{ "kind": "ssr", … }]
}

Assert a tier

A warning is easy to miss, and a component’s tier can change with an ordinary edit. To make the build fail instead, say in brust.toml how heavy each part of the app may get (the keys are in Configuration):

brust.toml
[tiers]
snapshot = "tiers.json"

[tiers.max]
"components/views/**" = "static"
"components/widgets/Map.tsx#default" = "react"

A component that compiles heavier than its pattern allows stops brust build with one tier error that lists every such component. Each starts with the file, line and name, then the reasons: for react, every fallback rule with its message and the fix; for native where static is required, what makes it interactive (state that is set, an event handler, an effect, a ref, a store read), with lines.

~/my-app
$ brust build
error tier components/views/Counter.tsx:4:1 Counter compiles to native; [tiers.max] "components/views/**" allows static
  state `count` is set (line 4)
  an event handler (line 6)

The compiler may make a copy of a component for some call sites (a React copy where the server cannot render it inside its parent). A copy is checked against its component’s pattern, and the error says which component places it. brust dev prints these as warning tier lines and keeps running.

The check runs after the compile has succeeded. A build error, such as list-key for a list whose items have no key, stops the build first and is the only thing printed. [tiers.max] guards a tier that changes, not code that does not build.

Keep a tier snapshot

[tiers] snapshot names a file that records every component’s tier. Commit it. The first build writes it (tiers: wrote tiers.json (… components)); every later build compares:

  • a component heavier than the file records fails the build, with the same reasons as above (… compiles to native; tiers.json records static);
  • a lighter, new or removed component prints one line (tiers: components/views/Card.tsx#default native -> static), and the file is left as it is;
  • when the change is wanted, brust build --update-tiers rewrites the file and prints each difference; review it like any other diff.
tiers.json
{
  "version": 1,
  "components": {
    "components/views/Badge.tsx#Badge": "static",
    "components/views/Counter.tsx#default": "native",
    "components/widgets/Map.tsx#default": "react"
  }
}

The snapshot lists the components of your app’s source, one entry per component, keyed path#Export. The copies the compiler makes for single call sites are checked against [tiers.max] but are not listed. Components compiled at run time with compileComponent (see Runtime components) are outside the check, which runs in brust build. brust dev never writes the file.

A component in a directory you list in [build] source_roots outside the app is keyed by its path from the app root, which starts with ../: "../shared/Stateful.tsx#Stateful" in the snapshot, and a pattern such as "../shared/**" in [tiers.max].