# Fluixi > Fluixi is a TypeScript framework for the web: fine-grained signals, JSX components that run once, and @fluixi/start for file routes, server rendering, server functions and static output. Fluixi is experimental: APIs change between alpha releases. Code remembered from an older alpha may no longer compile; check it against these rules and the installed version, and pin exact versions. The guide, page by page: https://docs.fluixi.com/llms.txt. Every page is also Markdown at its address plus `.md`, and the whole guide is at https://docs.fluixi.com/llms-full.txt. For the component library (buttons, forms, layout, skins), read https://ui.fluixi.com/llms.txt as well: an app using it follows its rules too. For forms (`@fluixi/forms`: fields, validation, schemas, submitting), read https://unpkg.com/@fluixi/forms@alpha/llms.txt, which ships in the package. ## Rules for writing Fluixi code Fluixi looks like React and works like Solid. Code written from React habits compiles and then fails to update. Read these before writing a component. ### Components run once - A component function runs one time. There is no re-render. Reactivity updates only the text, attribute or branch that reads a value. - No early `return` on a condition: it is decided once. Use ``. - No `cond() && ` for anything with state: it rebuilds `X`. Use ``. - No `.map()` for a list that changes. Use ``, with `by={(x) => x.id}` when the objects are recreated (refetched data). With `by`, the item is an accessor: `item().name`. Without `by`, the item is the value and the index an accessor: `i()`. - `` for primitives or fixed slots: item is an accessor, index a number. - Never call a component as a function. Write ``. - `class`, not `className`. ### State - In an app built by `@fluixi/start`, use the intrinsics with no import: `$signal`, `$memo`, `$effect`, `$store`, `$resource`, `$untrack`, `$batch`. In a package or library, import `signal`, `memo`, `effect`, `resource` from `@fluixi/reactive/signal`. - A signal is one handle: read `count()`, write `count.set(1)` or `count.set((n) => n + 1)`. There is no `.get()`. No `useState`, no tuple in new code. - Derive with `$memo(() => ...)`. No dependency arrays anywhere: reads are tracked. - Never write a signal from an effect to derive a value. Never create a signal or effect inside an effect or memo. - Set a new array or object; changing one in place and setting it again does not notify. - `$store({...})` for nested state: read `cart.lines`, write `cart.set('lines', 0, 'qty', 2)`. Assigning a store property does nothing. Stores wrap plain objects and arrays only. ### Effects and lifecycle - `$effect` runs on the server too. Browser APIs (`document`, `window`, `localStorage`) go in `onMount`, which runs only in the browser. - `onMount` does not track: a signal read inside it subscribes nothing. - Every listener, timer and subscription gets `onCleanup(() => ...)` next to it. - Refs: `let el!: HTMLInputElement;` then ``. Use the element in `onMount`. ### Props - Props are getters. Read `props.name` where it is used. `function C({ name })` is rewritten by the compiler to `props.name`; a destructure inside a nested block is not, and reads once. - Defaults: `mergeProps({ size: 'md' }, props)`. Forwarding: `splitProps`. - Read `props.children` once, or resolve it with `readChildren(() => props.children)`. ### Data and routing (apps built by `@fluixi/start`) - Routes are files in `src/routes`. Page data: `export const routeData = ...` returning a promise, read with `useRouteData()`. Not a resource and not `fetch` in `onMount`. - Shared cached reads: `cache(fn, 'name')`, invalidated with `revalidate('name')`. - Writes: `'use server'` functions and `action(fn, 'name')`. Every action has a name. - Navigation: `` and `useNavigate()` from `@fluixi/start/router`, not `` or `window.location` for in-app routes. - A resource read while loading suspends the nearest ``; failures go to the nearest ` ...}>`. `resource.latest` never suspends. - Server-only code lives in `*.server.ts` files, API routes, middleware and `'use server'` functions. Browser code may read only variables listed in `env.public`. ### Server render and hydration - The server and the browser must render the same markup. No `Date.now()`, `Math.random()` or browser checks during render: take the value from data, set it in `onMount`, or wrap the part in `` (imported from `@fluixi/core`). - Create resources unconditionally, in the same order on both sides. --- # Introduction Fluixi is a **compiler-native reactive framework**. Its compiler understands reactive values as values, not as a naming convention, and carries that understanding through JSX and `` html`` `` templates, DOM generation, SSR, hydration, routing and the meta-framework as one model. Because that model belongs to the compiler rather than to a debugger bolted on beside it, it can be read back: from source before anything runs, and from a running application in the editor, the browser and the playground. That is the whole idea, and it is worth being precise about what it buys, because "fine-grained reactivity" and "no virtual DOM" describe several frameworks and Fluixi is not trying to be a different spelling of any of them. ## The problem it goes after Every reactive framework asks you to keep a model in your head that the language does not share. You learn which reads are tracked, which values may be destructured, where a value has to stay a function, and which of your ordinary JavaScript habits will silently sever a dependency. The compiler cannot help, because it does not know what any of your values are, so the burden lands on you, and the failures are quiet: a stale label, a list that stops updating, nothing thrown. Fluixi's answer is to make the compiler know. It resolves a reactive primitive by the binding it came from, not by how the name reads: ```ts import { signal as state } from '@fluixi/reactive/signal'; const count = state(0); // a signal, resolved through the import function signal() { return 42; } const value = signal(); // not a signal, a local function ``` From there it can do things a runtime alone cannot. Destructure a component's props and the compiler rewrites the bindings into live reads, so the plain syntax keeps working: ```tsx function Card({ title, ...rest }) { return

{title}

; } ``` Where it cannot prove a rewrite is safe, it leaves your code exactly as written and says why. That is the contract: **normal TypeScript, with the compiler carrying the reactivity, and telling you when it can't.** ## What follows from that - **One model, two syntaxes.** JSX and `` html`` `` templates compile to the same reactive representation. Neither is a port of the other. - **Direct DOM.** A change runs the specific binding that depends on it. There is no component re-render, no diff, no virtual tree. - **The same model end to end.** Client rendering, SSR, hydration, the router and the meta-framework share one reactive graph rather than agreeing at the edges. - **Two ways to write a primitive, one primitive.** `signal(0)` and `$signal(0)` compile to the same call. The `$` form skips the import; the explicit API stays public, because a library that never runs this compiler still has to be able to write reactive code. ## The primitives ```ts import { signal, memo, effect } from '@fluixi/reactive/signal'; const count = signal(0); // state const doubled = memo(() => count() * 2); // derived effect(() => console.log(doubled())); // side effect ``` Inside a compiled app, drop the import: `$signal`, `$memo` and `$effect` are the same primitives, resolved by the compiler. - A **signal** holds a value and tracks who reads it. Call it to read, `.set()` to write. - A **memo** derives a value and recomputes only when its dependencies change. - An **effect** runs a side effect and re-runs when its reactive reads change. The reactive core, `@fluixi/reactive`, is a standalone library implementing the **TC39 Signals** model: a glitch-free, lazy, push-pull dependency graph you can use in the browser, on the server, or entirely on its own. ## Where Fluixi sits It borrows openly. Signals and fine-grained tracking are proven ideas; so is compiling templates to imperative DOM calls, and so is a meta-framework over SSR and routing. None of that was invented here, and pretending otherwise would be silly. What is Fluixi's own is the **contract between compiler and reactive graph**, and how far it reaches: one semantic model from a value's creation, through aliasing and destructuring and derived computations, into generated DOM bindings, across SSR and hydration, and out to disposal. Judge it on whether writing ordinary TypeScript keeps working, not on the feature list. ## With a coding assistant Assistants have seen far more React than Fluixi, and React habits compile in Fluixi but do not update. Give yours the rules and the guide before it writes code: - [`/llms.txt`](https://docs.fluixi.com/llms.txt): the rules, then every page with a one-line summary; - [`/llms-full.txt`](https://docs.fluixi.com/llms-full.txt): the rules and the whole guide in one file; - any page as Markdown: add `.md` to its address. Next: **[Quickstart](/v1/en/quickstart)**. --- # Quick start The fastest way to a running app is the `create-fluixi` scaffolder: ```bash npm create fluixi@latest my-app # or: pnpm create fluixi my-app · yarn create fluixi my-app ``` The scaffolder asks the following questions in order: - **App mode**, **SSR** (server-rendered via `@fluixi/start`) or **SPA** (client-only via Vite) - **Template syntax**, **JSX** (default) or **html``** (plain `.ts` files, no JSX) - **Component library**, **none** or **`@fluixi-ui`** (kit and tokens; components installed as needed) - **Styling**, **plain CSS**, **Tailwind CSS v4**, or **`@fluixi-css`** - **Authentication**, **none**, **OAuth2/OIDC** (identity provider, tokens in browser or on server), or **Better Auth** (SSR apps only) Then: ```bash cd my-app npm install npm run dev ``` New apps start on Vite 8 and TypeScript 7. Vite 8 needs Node 20.19 or later, or 22.12 or later. You can also skip the prompts: ```bash npm create fluixi@latest my-app -- --ssr --jsx # or --spa / --html npm create fluixi@latest my-app -- --ssr --auth=oauth2 --provider=keycloak --tokens=server ``` Each question is represented by a flag, so any question answered on the command line is not asked again. Authentication flags include `--auth=oauth2`, `--auth=better-auth`, or `--no-auth`; when using `oauth2` you can also give `--provider` and `--tokens`. Google and Dex store tokens on the server, therefore `--tokens=browser` is refused with those providers, and an SSR app is required for authentication, so `--spa` combined with `--auth` is refused. ## JSX or html``? Fluixi compiles **both** JSX and tagged `` html`` `` templates to the same fine-grained DOM calls. Pick whichever you prefer, or mix them in one file. ```tsx // JSX, needs `jsx` configured in tsconfig function Counter() { const n = $signal(0); return ; } ``` ```ts // html``, plain .ts, no jsx in tsconfig import { html } from '@fluixi/core'; function Counter() { const n = $signal(0); return html``; } ``` Choose **html``** when you don't want to configure JSX (for example a library, a script, or a plain-TypeScript codebase). See **[html`` templates](/v1/en/html-templates)** for the full syntax. Every scaffolded app includes **[@fluixi/ts-plugin](/v1/en/html-templates)**, which gives `` html`` `` templates real TypeScript support in your editor, hover, completion and type-checking inside the template. It runs in the editor's built-in TypeScript, also for a project on TypeScript 7: see [Editor support](/v1/en/html-templates#editor-support). ## Add a component or route The CLI scaffolds pieces into an existing app, matching your project's syntax automatically: ```bash npx fluixi generate component Button # → src/components/Button.tsx (or .ts for html``) npx fluixi generate route about # → src/routes/about.tsx ``` ## Add authentication ```bash npx fluixi add auth # asks npx fluixi add auth oauth2 --provider keycloak --tokens server npx fluixi add auth better-auth --no-install ``` The command asks whether you want OAuth2/OIDC or Better Auth, then prompts for the OAuth2 provider and token location unless flags answer them, with the same flags as `create-fluixi`. It writes the same files that `create-fluixi` creates for a new app, preserving any existing files and printing lines to add to uneditable configs. The package is installed with the project's package manager, unless `--no-install` is used. Then copy `.env.example` to `.env` and register the redirect URI with the provider. See the documentation for [OAuth2](/v1/en/oauth2) and [Better Auth](/v1/en/better-auth). ## Starting from scratch If you'd rather wire it up yourself, install the runtime and the Vite plugin: ```bash npm install @fluixi/core npm install -D @fluixi/vite-plugin vite ``` ```ts // vite.config.ts import { defineConfig } from 'vite'; import { fluixi } from '@fluixi/vite-plugin'; export default defineConfig({ plugins: [fluixi()] }); ``` ```ts // src/main.ts import { render, html } from '@fluixi/core'; import { App } from './app'; render(() => html`<${App} />`, document.getElementById('app')!); ``` ## Which build am I running? Whichever way you mount, `render` from `@fluixi/core`, or hydration through `startClient`, the mount element carries `data-fluixi`. In development the attribute holds the release and the versions actually running are exposed as `window.Fluixi`; in production the attribute is empty and the global absent, so a deployed page says it runs Fluixi without naming the release. `@fluixi/start` writes it on the server as well, so it shows in the page source: ```html
``` ```js > window.Fluixi { core: '1.0.0', dom: '1.0.0', reactive: '1.0.0' } ``` These three ship as one release. If they disagree, the console says so, a mismatch means a stale lockfile or two copies resolved side by side, which otherwise surfaces much later as reactivity that makes no sense. Continue to **[Signals](/v1/en/signals)** for the reactive core, or jump to **[html`` templates](/v1/en/html-templates)**. --- # Coming from React, Solid or Next.js What carries over, what changes, and the habits to drop. Each section maps what you know to its Fluixi equivalent and links to the page that explains it. ## From React The biggest change: **a component runs once.** There is no re-render. State is held in signals, and a change updates only the text, attribute or branch that reads it. Most React habits come from re-rendering, and most of them can go. | React | Fluixi | |---|---| | `const [n, setN] = useState(0)` | `const n = $signal(0)`, read `n()`, write `n.set(1)` | | `useMemo(() => a * b, [a, b])` | `$memo(() => a() * b())`: no dependency array, reads are tracked | | `useEffect(() => {...}, [dep])` | `$effect(() => {...})`; `onMount` for code that runs once in the browser | | effect cleanup `return () => ...` | `onCleanup(() => ...)`, or the function `onMount` returns | | `useRef` | `let el!: HTMLElement` and `ref={el}`; a plain variable for anything else | | `useCallback` | a plain function: the component does not run again, so nothing is recreated | | `React.memo` | nothing: there are no re-renders to skip | | `{cond && }` | `` | | `list.map(x =>
  • )` | ` x.id}>` | | `useContext` / `createContext` | the same names, from `@fluixi/core` ([Context](/v1/en/context)) | | `useReducer`, nested state | `$store` with path setters ([Stores](/v1/en/stores)) | | ``, `lazy` | the same, plus `load:visible` and friends on any tag ([Loading strategies](/v1/en/load-strategies)) | | `className` | `class`, and `classList={{ active: on() }}` | | `useId` | `createUniqueId()` | Habits to drop: - **Dependency arrays.** A memo or an effect tracks what it reads, each time it runs. There is nothing to keep in sync, and no stale closure. - **Destructuring props at the top and expecting it to stay current.** The compiler keeps it live in the plain cases; a nested destructure reads once and the build warns ([Components](/v1/en/components)). - **Early returns.** `if (!user) return ` is decided once; use ``. - **Setting state in an effect to derive it.** Use a memo. - **Worrying about render cost.** Splitting a component does not change what updates. ## From Solid Fluixi is close to Solid: fine-grained signals, components that run once, the same control-flow components. What differs: | Solid | Fluixi | |---|---| | `const [n, setN] = createSignal(0)` | `const n = signal(0)` (or `$signal` in an app): one handle, `n()` and `n.set()`. `createSignal` still exists, returning the tuple | | `createMemo`, `createEffect`, `createResource` | `memo`, `effect`, `resource`, and their `$` forms with no import | | `createStore` returns `[state, setState]` | `$store(...)` returns one handle: read `cart.lines`, write `cart.set('lines', ...)` | | `` | the same; add `by={(x) => x.id}` to keep rows for recreated objects | | `mergeProps`, `splitProps`, `children()` | `mergeProps`, `splitProps`, `readChildren()` | | `splitProps` to keep props live when destructuring | write `function C({ title })`: the compiler rewrites it to `props.title` | | `createEffect` skipped on the server | **an effect runs on the server too**; use `onMount` for browser-only work ([Effects](/v1/en/effects)) | Also new: dependency injection with `inject()` and app modules ([Dependency injection](/v1/en/dependency-injection)), custom elements as first-class components ([Web components](/v1/en/web-components)), and `load:` strategies on any tag. ## From Next.js `@fluixi/start` covers what Next.js does for an app (file routes, server rendering, server code, middleware, static output), with a different model for data: there are no server components. Every route component renders on the server and hydrates in the browser; data comes in through `routeData`. | Next.js | Fluixi start | |---|---| | `app/blog/[slug]/page.tsx` | `src/routes/blog/[slug].tsx` ([Routing](/v1/en/routing)) | | `layout.tsx` | a layout route rendering `` | | `async` server component fetching data | `export const routeData = ...` in the route file, read with `useRouteData()` | | `fetch(..., { next: { revalidate } })` | `cache(fn, 'name')` and `revalidate('name')` ([Caching](/v1/en/caching)) | | Server Actions | `'use server'` functions and `action(fn, 'name')` ([Server functions](/v1/en/server-functions)) | | `app/api/.../route.ts` | API routes ([API routes](/v1/en/api-routes)) | | `middleware.ts` | middleware ([Middleware](/v1/en/middleware)) | | `metadata` / `generateMetadata` | `seo()` ([SEO](/v1/en/seo)) | | `next/link`, `useRouter().push` | ``, `useNavigate()` | | `useParams`, `useSearchParams` | the same names, from `@fluixi/start/router` | | `generateStaticParams`, static export | [Static generation](/v1/en/static-generation) | | `NEXT_PUBLIC_*` | names listed in `env.public` ([Environment](/v1/en/environment)) | | `'use client'` | not needed: every component runs in the browser; mark server-only files `*.server.ts` | | `next/image` | [Images](/v1/en/images) | To keep code off the client, there is no `'use client'` boundary to manage. Server-only code goes in `*.server.ts` files, `'use server'` functions, API routes and middleware, and the build refuses an import of a server file from browser code. To ship less JavaScript for a part of the page, defer it with `load:visible`, `load:idle` or `load:never`. Next: **[Troubleshooting](/v1/en/troubleshooting)**. --- # CDN & bundles Every Fluixi runtime package ships a self-contained **IIFE global build** you can drop into a page with a single ` ``` ## The reactive API, `window.Fluixi` The ergonomic `createSignal`/`createMemo`/`createEffect`/`createStore` surface, on the same core: ```html ``` ## A reactive UI, `window.FluixiDOM` The DOM runtime plus the reactive API, so one script builds a live interface. It re-exports the reactive primitives (dom no longer bundles them itself), so you don't need a second file. ```html
    ``` ## The whole framework, `window.Fluixi` `core.global.js` bundles everything, reactivity, components, control flow, the router, and `startClient`. Use it when you want the full framework without a build. Its reactive API is the `createSignal` / `createMemo` / `createEffect` form; the `signal` / `memo` / `effect` handles of `@fluixi/core` as a module are not on the global: ```html
    ``` > `reactive.global.js`, `core.global.js` and `fluixi.global.js` all expose `window.Fluixi`, load > **one** of them, not several. `signal.global.js` uses `window.Signal` and can sit alongside either. ## Templates in the page, `window.Fluixi` `` html`` `` needs the full build because the compiler normally replaces the tag at build time; `fluixi.global.js` carries the compiler itself, so a page with no build step compiles its templates as it renders. The other globals ship the runtime only. ```html
    ``` A component is reachable as a bare `` once it is passed to `define()`, and as `` <${Counter} /> `` without registering anything. Pages that compile elsewhere, or that build nodes through the runtime API directly, use the other globals. `dom.global.js` and `core.global.js` are smaller for that reason. Compiling in the page evaluates the code it emits, so a Content-Security-Policy without `unsafe-eval` blocks the full build. The other globals are unaffected. ## Bare imports, `@fluixi/cdn` A global puts one object on `window`, and `reactive`, `core` and `fluixi` all claim the same name, so only one may be loaded. With a map the page writes the same `import` statements a built app writes, and loads only the subpaths it touches. A browser resolves a bare specifier only through a map and never reads package.json, so every transitive subpath has to be listed; `@fluixi/cdn` is that list, generated per release and pinned to it. Each entry points at a bundled copy shipped in `@fluixi/cdn` rather than at the package's own files, so a page importing `@fluixi/core` fetches about 25 files instead of one per module. - `min.js` (20 entries): core, dom, utils and the graph behind them - `templates.js` (3 entries): adds compiling `html`` in the page - `full.js` (23 entries): everything a browser can use The `.js` installs the map. Put it before the first module script: recent Chromium accepts a map added after modules started loading, but browsers that do not support several import maps ignore it. ```html
    ``` `html`` needs the template runtime, and the `html` re-exported from `@fluixi/core` is the tag the compiler replaces at build time; calling it in the page throws. ```html
    ``` The `.json` is there for a page that would rather hold the map in its own markup. Several maps in one page need Chromium 133 or newer, which is why `full` exists as one file. `@fluixi-ui/cdn` carries the same thing for the component library and composes with these, since neither repeats the other's entries. ## Development builds Every file above is a production build: minified, with Fluixi's development warnings and the devtools reporting left out. While building a page, load the development build instead. It has the same API at the same path with `/dev/` added, unminified, and it warns about mistakes such as a promise passed as a child: ```html ``` The import maps work the same way: `min.development.js`, `templates.development.js` and `full.development.js` point at development bundles, and the `.json` files have the same counterparts. ```html ``` A development build is about twice the size, so switch back to the production file before deploying. ## Version pinning `unpkg.com/@fluixi/core@1/...` follows the major; pin an exact version for reproducibility, e.g. `unpkg.com/@fluixi/core@1.0.0-alpha.79/dist/cdn/core.global.js`. jsDelivr works the same: `cdn.jsdelivr.net/npm/@fluixi/core/dist/cdn/core.global.js`. For real apps, prefer the compiled path (`npm create fluixi`): the compiler produces smaller, tree-shaken output than any single global bundle. The CDN builds are for demos, prototypes, CodePen/JSFiddle, and dropping reactivity into an existing page. --- # Signals A **signal** holds one piece of state that changes. Read it by calling it, write it with `.set()`. Everything that read it updates: a text node, an attribute, a memo, an effect. Nothing else runs again. ```ts import { signal } from '@fluixi/reactive/signal'; const count = signal(0); count(); // read → 0 count.set(1); // write → 1 count.set(c => c + 1); // update from the previous value → 2 ``` Inside a start app, `$signal` is the same thing without the import: the compiler resolves it and adds what it needs. ```ts const count = $signal(0); ``` ## A realistic example A quantity picker for a cart line. Each signal is read where it is shown, so a click updates two text nodes and one attribute, and the component function does not run again. ```tsx function Quantity(props: { price: number; max: number }) { const qty = $signal(1); const atMax = () => qty() >= props.max; return (
    {qty()} {(qty() * props.price).toFixed(2)} €
    ); } ``` `atMax` is a plain function: it costs nothing to create and is computed where it is read. When several places read a derived value, or it is costly, make it a memo ([Derived values](/v1/en/derived-values)). ## Reading is tracking Calling a signal inside a memo, an effect or a JSX expression **subscribes** that place to it. The next write updates only the places that read it: ```ts effect(() => { console.log('count is', count()); // subscribes to count }); count.set(5); // logs "count is 5" ``` Reading outside any reactive place (in an event handler, at module level) just returns the value. ## Writing Effects that read a signal run right after each write. Several writes in a row each flush their effects, so group them with `batch` when they belong together: ```ts import { batch } from '@fluixi/reactive/signal'; function reset() { batch(() => { query.set(''); page.set(1); sort.set('name'); }); // effects that read all three run once, here } ``` An event handler does not batch for you. ## Equality A write is skipped when the new value is `===` the old one (`Object.is`), so readers are not notified for nothing. Pass `equals` to decide what counts as a change, or `equals: false` to notify on every write: ```ts const user = signal(initial, { equals: (a, b) => a.id === b.id && a.name === b.name }); const tick = signal(undefined, { equals: false }); // a trigger: every write notifies ``` ## Reading without subscribing `untrack` reads without creating a dependency: ```ts import { untrack } from '@fluixi/reactive/signal'; effect(() => { draw(count(), untrack(theme)); // runs again on count, not on theme }); ``` `$untrack` is the same without the import. ## Where to use it, and where not Use a signal for a value that changes and that the UI shows or depends on: a form field, a selected tab, a counter, a toggle. **Not for a value computed from other state.** An effect that writes a signal from other signals runs one step late and can loop. Derive it: ```ts // ✗ a copy kept in sync by hand const total = signal(0); effect(() => total.set(price() * qty())); // ✓ derived const total = memo(() => price() * qty()); ``` **Not for an object or array changed in place.** The same reference fails the equality check, so nothing updates: ```ts // ✗ same array: no reader is notified items.set(list => { list.push(item); return list; }); // ✓ a new array items.set(list => [...list, item]); ``` For nested objects and lists edited key by key, a [store](/v1/en/stores) tracks each key on its own. **Not at module level for per-user state in a server-rendered app.** One module instance serves every request on the server, so a signal declared at the top of a file is shared by all visitors. Create it in a component, or keep per-request state in a [service](/v1/en/dependency-injection) or the request's locals. **Not created inside an effect or a memo.** Their body runs again on every change and builds a new signal each time, losing the old value. Create signals once, in the component body. ## The tuple form `createSignal` returns the same signal as a `[read, write]` pair: ```ts import { createSignal } from '@fluixi/reactive/signal'; const [count, setCount] = createSignal(0); count(); // read setCount(1); // write ``` It is one primitive with two spellings: `signal` is `createSignal` with the write function attached as `.set`. They track each other, mix freely in a module, and behave the same through server rendering and hydration. Prefer `signal`; the tuple is there for code ported from Solid and for when you want the two halves apart. ## Under the hood A signal is a node in a reactive graph that follows the shape of the TC39 Signals proposal. A write marks the nodes that read it as dirty and pushes that mark down the graph; a memo recomputes only when something reads it and one of its sources really changed. Effects are flushed synchronously after the write (or at the end of a `batch`). The graph's state lives on `globalThis`, so two copies of the package on one page share it. See [TC39 signals](/v1/en/tc39-signals) for the lower-level API. ## Intrinsics In an app built by `@fluixi/start`, the `$` forms need no import: the compiler rewrites each to the runtime call and adds the import. They are not a second reactive system: `$signal` compiles to `signal`. A local binding of the same name wins, and the compiler says so. | Intrinsic | Stands for | Imported from | | --- | --- | --- | | `$signal`, `$memo`, `$effect` | `signal`, `memo`, `effect` | `@fluixi/reactive/signal` | | `$resource` | `resource` | `@fluixi/reactive/signal` | | `$cachedResource` | `cachedResource` | `@fluixi/reactive/cached-resource` | | `$store`, `$untrackStore` | `store`, `untrackStore` | `@fluixi/reactive/store` | | `$untrack`, `$batch`, `$root`, `$context` | `untrack`, `batch`, `root`, `context` | `@fluixi/reactive/signal` | | `$cleanup` | `onCleanup` | `@fluixi/reactive/signal` | | `$renderEffect`, `$computed` | `renderEffect`, `computed` | `@fluixi/reactive/signal` | | `$selector`, `$deferred` | `createSelector`, `createDeferred` | `@fluixi/reactive/signal` | | `$storage`, `$asyncStorage`, `$persisted` | `useStorage`, `useAsyncStorage`, `persisted` | `@fluixi/core/storage` | | `$env` | `env` | `@fluixi/start/env` | | `$html`, `$svg`, `$css` | `html`, `svg`, `css` | `@fluixi/core` | Package code, which the start compiler does not process, imports the runtime names. Next: **[Derived values](/v1/en/derived-values)**. --- # Derived values A **memo** is a value computed from other reactive values. It caches its result and recomputes only when one of the values it read has changed. ```ts import { signal, memo } from '@fluixi/reactive/signal'; const first = signal('Ada'); const last = signal('Lovelace'); const fullName = memo(() => `${first()} ${last()}`); fullName(); // "Ada Lovelace" ``` `$memo` is the same without the import: ```ts const fullName = $memo(() => `${first()} ${last()}`); ``` ## A realistic example A searchable, sorted product list. The filtered list is read by the list and by the count, so it is computed once per change and shared: ```tsx function Catalog(props: { products: Product[] }) { const query = $signal(''); const sort = $signal<'name' | 'price'>('name'); const visible = $memo(() => { const q = query().trim().toLowerCase(); const found = props.products.filter((p) => p.name.toLowerCase().includes(q)); return found.sort((a, b) => (sort() === 'name' ? a.name.localeCompare(b.name) : a.price - b.price)); }); return (
    query.set(e.currentTarget.value)} placeholder="Search" />

    {visible().length} products

      p.id}> {(p) =>
    • {p().name}, {p().price} €
    • }
    ); } ``` Typing a letter recomputes `visible` once; the count's text node and the rows that changed update. `by` keeps the rows that stay, so their DOM is not rebuilt ([Control flow](/v1/en/control-flow)). ## Lazy and cached A memo computes only when it is **read**, and recomputes only when one of its sources really changed. Reading it again returns the cached value: ```ts const expensive = memo(() => heavyCompute(data())); expensive(); // computes once expensive(); // cached, no recompute ``` A memo nothing reads never runs. ## Glitch-free When a change fans out and meets again, a memo recomputes **once**, with consistent inputs, never with a half-updated value: ```ts const a = signal(1); const b = memo(() => a() + 1); const c = memo(() => a() * 2); const d = memo(() => b() + c()); a.set(2); // d recomputes a single time, with b and c both updated ``` ## The previous value and equality The function receives its previous result, which makes an accumulator cheap without a second signal; the second argument is the starting value: ```ts const highest = memo((prev = 0) => Math.max(prev, reading()), 0); ``` As with signals, `equals` decides what counts as a change for the memo's own readers: ```ts const bounds = memo(() => measure(items()), undefined, { equals: (a, b) => a.width === b.width && a.height === b.height, }); ``` ## Many rows asking "is it me?" A list where one row is selected: with a plain comparison in each row, changing the selection re-runs the comparison in every row. `createSelector` gives each key its own boolean, so only the row that was selected and the row that now is update: ```tsx import { createSelector } from '@fluixi/reactive/signal'; const selected = $signal(null); const isSelected = createSelector(selected); r.id}> {(row) => selected.set(row().id)}>...} ``` ## Keeping the page responsive `createDeferred(source, { timeoutMs })` follows a value but applies its updates when the browser is idle (or after `timeoutMs`). Typing stays smooth while a heavy view built from the value catches up: ```ts import { createDeferred } from '@fluixi/reactive/signal'; const deferredQuery = createDeferred(query, { timeoutMs: 200 }); const results = memo(() => search(deferredQuery())); ``` ## Where to use it, and where not Use a memo for a value derived from state that several places read, or that costs something to compute: a filtered list, a total, a formatted date, a permission check. **Not for a cheap value read once.** A plain function does the same with less bookkeeping: ```ts const label = () => `${count()} items`; // enough when only one place reads it ``` **Not for side effects.** A memo runs when it is read, maybe never, maybe late; writing a signal, fetching or logging there does not happen when you expect. Use an [effect](/v1/en/effects), or a [resource](/v1/en/async) for data. **Not creating signals or effects inside it.** They are rebuilt on every recompute. Create them once in the component body. **Not to copy a value into a signal.** If you find an effect that writes a signal from other signals, it should be a memo. ## Under the hood A memo is a computed node in the reactive graph. A write to one of its sources marks it "maybe dirty"; the next read checks its sources in order and recomputes only if one of them really produced a new value, then stores the result. Readers of the memo are notified only when its own value changed, according to `equals`. ## The accessor form `createMemo` is the same primitive under its older name: ```ts import { createMemo } from '@fluixi/reactive/signal'; const fullName = createMemo(() => `${first()} ${last()}`); fullName(); // "Ada Lovelace" ``` `memo` returns that same accessor, so the two mix freely with signals written either way. Next: **[Effects](/v1/en/effects)**. --- # Effects An **effect** is how reactive state reaches the world outside it: a third-party library, a timer, the console, the network. It runs once to learn what it reads, then again after each change to any of it. ```ts import { signal, effect } from '@fluixi/reactive/signal'; const volume = signal(0.5); effect(() => { player.setVolume(volume()); // runs again whenever volume changes }); ``` `$effect` is the same without the import. `createEffect` is the same function under its original name, and everything below applies to both. You rarely need one for the page itself: what JSX shows already updates on its own. Effects are for the things the framework does not draw. ## A realistic example A chart from a third-party library, kept in step with the data. The chart is created once the element exists, updated by an effect, and destroyed with the component: ```tsx import { onMount, onCleanup } from '@fluixi/core'; function SalesChart(props: { points: () => number[] }) { let canvas!: HTMLCanvasElement; let chart: Chart | undefined; onMount(() => { chart = new Chart(canvas, { data: props.points() }); onCleanup(() => chart?.destroy()); }); $effect(() => { const points = props.points(); // read on every run, so the effect follows the data chart?.update(points); }); return ; } ``` `onMount` runs in the browser only, after the element is in the page; the effect then keeps the chart in step with every change of `points`. ## Effects run on the server too During a server render, an effect runs once like the rest of the component. Code that needs the browser (`window`, `document`, `localStorage`, an element's measurements) belongs in `onMount`, or behind a check: ```ts $effect(() => { document.title = title(); // ✗ throws on the server: there is no document }); onMount(() => { // ✓ browser only, after the element is in the page }); ``` ## Cleanup Register cleanup with `onCleanup`. It runs before the effect runs again and when its owner goes: timers, listeners and subscriptions. ```ts import { onCleanup } from '@fluixi/reactive/signal'; effect(() => { const id = setInterval(tick, delay()); onCleanup(() => clearInterval(id)); // cleared before the next run, and on dispose }); ``` ## Previous value The effect receives its previous return value, to compare across runs: ```ts effect((prev) => { const value = count(); if (prev !== undefined && prev !== value) report(prev, value); return value; }); ``` ## Naming The third argument names the effect for the devtools graph, as signals and memos take a name: ```ts effect(() => syncTitle(title()), undefined, { name: 'sync title' }); ``` An unnamed effect shows as one of many; a named one says what it is for when you are tracking down why something ran again. ## Batching Effects run right after each write. Several writes inside `batch` run their dependent effects **once**, after the batch: ```ts import { batch } from '@fluixi/reactive/signal'; batch(() => { first.set('Grace'); last.set('Hopper'); }); // effects depending on both run a single time ``` ## Where to use it, and where not Use an effect to push reactive state into something the framework does not manage: a chart, a map, a media player, an analytics call, a WebSocket subscription that depends on a signal. **Not to derive state.** An effect that writes a signal from other signals is a memo written the long way, and runs one step late: ```ts // ✗ effect(() => fullName.set(`${first()} ${last()}`)); // ✓ const fullName = memo(() => `${first()} ${last()}`); ``` **Not to write a signal it reads.** It triggers itself; read it with `untrack` if you need its current value. **Not to update the page.** `{count()}`, `class={...}` and the other JSX expressions already update the exact node; an effect writing `textContent` duplicates the framework's work. **Not to load data.** A [resource](/v1/en/async) or the route's `routeData` loads data, tracks loading and errors, and sends the result with the server render; an effect calling `fetch` does none of that. **Not for the head or for storage.** `seo()` keeps the title and meta tags in step ([SEO](/v1/en/seo)), and `persisted` keeps a signal in storage ([Storage](/v1/en/storage)), both on the server too. ## Under the hood An effect is a node in the reactive graph with no readers of its own. When one of its sources changes, it is queued and run synchronously after the write, or at the end of the `batch`. Effects created by a component belong to its owner and are disposed with it, their cleanups included. Next: **[Stores](/v1/en/stores)**. --- # Stores A signal holds one value. A **store** holds nested state, objects and arrays, and tracks each key on its own: reading `cart.total` subscribes to `total` only, so a change to `cart.items` does not disturb it. ```ts import { store } from '@fluixi/reactive/store'; const cart = store({ items: [] as Item[], total: 0, }); cart.total; // read a property reactively cart.set('total', 42); // update one property: only readers of total update ``` You read a store's properties directly: it is an object, and the property access **is** the reactive read, where a signal is a value you call. `$store` is the same without the import: ```ts const cart = $store({ items: [], total: 0 }); ``` ## A realistic example A cart where each line's quantity changes on its own. Changing one quantity updates that line's number and the total, and nothing else: ```tsx type Line = { id: string; name: string; price: number; qty: number }; function Cart() { const cart = $store({ lines: [] as Line[], coupon: '' }); const total = $memo(() => cart.lines.reduce((sum, l) => sum + l.price * l.qty, 0)); const add = (line: Line) => cart.set('lines', (lines) => [...lines, line]); const setQty = (i: number, qty: number) => cart.set('lines', i, 'qty', qty); const remove = (id: string) => cart.set('lines', (lines) => lines.filter((l) => l.id !== id)); return (
    l.id}> {(line, i) => (
    {line().name} setQty(i(), e.currentTarget.valueAsNumber)} />
    )}

    Total: {total().toFixed(2)} €

    ); } ``` ## Writing The state is read-only from the outside: assigning `cart.total = 1` does nothing. Every change goes through `set`, which is what lets the store know exactly what changed. ```ts cart.set('total', 42); // one key cart.set('total', (t) => t + 1); // from the previous value cart.set('lines', 0, 'qty', (q) => q + 1); // a path, one step per argument cart.set('lines.0.qty', 3); // the same path as a string cart.set({ coupon: 'WELCOME' }); // merge keys at the top level cart.set('lines', (lines) => [...lines, item]); // replace an array with a new one ``` A reader of `cart.total` is **not** disturbed by a write to `cart.lines`: that is the point of a store over a signal holding an object. ## Reading in computations Reading a store property inside a memo, an effect or JSX subscribes to that property alone: ```ts const itemCount = memo(() => cart.lines.length); // tracks the list's length only ``` Signals are created lazily, one per key something actually reads, so a large store costs what the page looks at, not its size. ## Where to use it, and where not Use a store for state with structure that changes in parts: a form with many fields, a cart, a board of cards, editor state, settings. **Not for a single value.** A store around `{ value: 0 }` is a signal with extra steps. **Not for `Map`, `Set`, `Date` or class instances inside it.** A store tracks plain objects and arrays; other values are stored as they are, and a change inside them is not seen. Keep plain data in the store, or replace the whole value through `set`. **Not when the state needs a key named `set`.** The handle uses `set` for its setter; use the tuple form below. **Not shared at module level in a server-rendered app.** As with signals, one module instance serves every request on the server. Create the store in a component, or provide it per request with [dependency injection](/v1/en/dependency-injection). ## Snapshots `unwrap(cart)` returns the plain object behind the store, for `JSON.stringify` or a request body. `untrackStore(cart)` does the same without subscribing the current computation. ## A mutable store `createMutableStore` drops the setter: assigning a property is a tracked write. It suits state local to one component, where a setter buys nothing; the cost is that a change can come from anywhere holding the object. ```ts import { createMutableStore } from '@fluixi/reactive/store'; const form = createMutableStore({ name: '', email: '' }); form.name = 'Ada'; // readers of form.name update ``` ## The tuple form `createStore` returns the same store as a `[state, setter]` pair: ```ts import { createStore } from '@fluixi/reactive/store'; const [cart, setCart] = createStore({ items: [], total: 0 }); cart.total; setCart('total', 42); ``` `store` is that pair with the setter attached to the state, so both are one primitive. Use `createStore` when your state needs a `set` key of its own: the attached setter would hide it. ## Under the hood A store is a proxy over a plain object. Reading a key through the proxy creates (on first read) a signal for that key and subscribes the current computation to it; nested objects are wrapped the same way when read. `set` resolves the path, writes the raw object, and notifies only the keys whose values changed. Arrays track their indexes and `length`. Next: **[Async data](/v1/en/async)**. --- # Async data A **resource** turns something asynchronous (a fetch, a query, anything that returns a promise) into a value the page can read, with its loading and error state: ```ts import { signal, resource } from '@fluixi/reactive/signal'; const userId = signal(1); const user = resource(userId, async (id) => { const res = await fetch(`/api/users/${id}`); return res.json(); }); user(); // the value; reading it while loading suspends the nearest user.loading; // true while a fetch runs user.error; // the failure, once it failed user.latest; // the last value that arrived, kept during a refetch: never suspends user.state; // 'unresolved' | 'pending' | 'ready' | 'refreshing' | 'errored' user.refetch(); // fetch again with the same source user.mutate(v); // set the value directly (an optimistic update) ``` `$resource` is the same without the import. The first argument is a reactive **source**: whenever it changes, the fetcher runs again with the new value, and a newer fetch wins over an older one still in flight. Omit it to fetch once. Data a page needs before it shows belongs in the route's `routeData` ([Routing](/v1/en/routing)); a resource is for data a component loads for itself. ## A realistic example A user card that loads its user, shows a placeholder while loading and a retry on failure: ```tsx function UserCard(props: { id: string }) { const user = $resource(() => props.id, (id) => fetch(`/api/users/${id}`).then((r) => r.json())); return ( (

    Could not load the user.

    )}> }>

    {user()?.name}

    {user()?.email}

    ); } ``` Changing `props.id` fetches the new user, and the skeleton shows again until it arrives. ## Suspense: what shows while loading `` shows its fallback while any resource read below it is loading, and its content once all of them are in. Put one around each region that should appear at once; two regions that load separately get two boundaries. A refetch brings the fallback back. To keep the current content on screen instead: - read `user.latest` where the previous value is fine to show: it never suspends; - or make the change inside a transition (below). `SuspenseList` orders sibling boundaries: `revealOrder="forwards"` shows them top to bottom even when the network answers out of order, and `tail="collapsed"` shows only the next fallback. Use it for feeds and dashboards that would otherwise jump. ## ErrorBoundary: what shows when something fails ` ...}>` catches what a component, an effect or a resource below it throws, and shows the fallback instead; `reset()` renders the children again. Put one around each region that can fail on its own, and one around the routes in the root layout. Without any, the error is uncaught: in the console in the browser, a `500` for a server render. ## Transitions A change made inside `startTransition` keeps the page as it is while the loads it causes run: a resource reloading because of it keeps returning its current value instead of suspending. `useTransition` says whether such a load is still running: ```ts import { useTransition } from '@fluixi/reactive/signal'; const [isPending, startTransition] = useTransition(); // The current tab stays on screen, dimmed by isPending(), until the next one has loaded. const open = (next: string) => startTransition(() => tab.set(next)); ``` `startTransition` returns a promise that settles once every load it started has. A resource loading for the first time has no value to keep, so it suspends as usual. ## Where to use it, and where not | You need | Use | |---|---| | data the page needs before it shows | the route's `routeData`, with `cache()` | | data a widget loads for itself | a resource, inside its own `Suspense` | | data several components read | `cachedResource` with a key, or `cache()` ([Caching](/v1/en/caching)) | | the page kept on screen while a filter reloads it | `startTransition`, or `.latest` | | a write to the server | a server function or an action, not a resource | **Not `fetch` in an effect or in `onMount`.** You lose the loading and error state, the server render does not wait for it, and the browser fetches again after hydration. **Not created conditionally.** On the server, each resource's value is sent with the page and picked up by position in the browser. A resource created on one side only (behind a browser check) shifts every one after it. Create resources unconditionally, in the same order on both sides. **Not for secrets.** Everything a resource returns is serialized into the page. Return only what the page shows. ## On the server On the server, Fluixi **waits** for every resource a render started before writing the HTML, then sends the values with the page, so the browser hydrates without fetching again: no loading flash, no waterfall. The head goes out first; the body follows in one piece once every resource has loaded, so the slowest one decides when the page appears. Content is not streamed in as each resource settles. ```ts // the same code renders on the server (awaited) and in the browser (seeded, no refetch): const posts = $resource(fetchPosts); ``` ## Under the hood A resource is a few signals (value, error, state, the current promise) and one effect that watches the source and starts the fetch. Reading the resource while it loads throws its promise, which the nearest `Suspense` catches and counts until it settles; a failure throws the error to the nearest `ErrorBoundary`. Each resource takes the next id in the render, which is how the browser finds the value the server sent for it. ## The tuple form `createResource` returns the same resource as `[resource, actions]`: ```ts import { createResource } from '@fluixi/reactive/signal'; const [user, { refetch, mutate }] = createResource(userId, fetchUser); user(); // the value user.loading; refetch(); ``` `resource` is that pair folded into one handle: the accessor `createResource` returns, with `refetch` and `mutate` attached, so suspending, tracking and server seeding are the same. Explore it live in the [Playground](https://playground.fluixi.com). --- # The TC39 Signals core The primitives you've seen, `createSignal`, `createMemo`, `createEffect`, are built on a small, standards-shaped core: an implementation of the **TC39 Signals proposal**. You rarely need it directly, but it's there when you want the lowest-level API or to build your own reactive abstractions. ## Signal.State A writable signal, the equivalent of `createSignal`: ```ts import { Signal } from '@fluixi/reactive/signal'; const count = new Signal.State(0); count.get(); // 0 count.set(1); count.get(); // 1 ``` It's equality-gated like `createSignal`; pass `{ equals }` to customize. ## Signal.Computed A lazy, cached derived signal, the equivalent of `createMemo`: ```ts const doubled = new Signal.Computed(() => count.get() * 2); doubled.get(); // recomputes only when count changes ``` A computed runs only when read, and only recomputes when a dependency it read actually changed, the same glitch-free, lazy behavior as a memo. ## Signal.subtle.Watcher `State` and `Computed` are **pull-based**: nothing runs on its own. To react *eagerly*, the basis of effects: use a `Watcher`. Its callback fires when a watched signal might have changed; it must not read signals itself, only schedule work: ```ts let queued = false; const w = new Signal.subtle.Watcher(() => { if (queued) return; queued = true; queueMicrotask(() => { queued = false; for (const node of w.getPending()) node.get(); // re-read to settle w.watch(); // re-arm }); }); w.watch(doubled); count.set(2); // schedules the watcher ``` `getPending()` returns the watched signals that may have changed; re-reading them settles the graph, and `watch()` re-arms the watcher. This is exactly how `createEffect` is implemented under the hood. ## subtle utilities The `Signal.subtle` namespace also exposes `untrack(fn)` (read without subscribing), `currentComputed()` (the computed currently evaluating, if any), and `hasSinks(signal)` (whether anything observes a signal). ## Why this matters Because the core follows the TC39 model, your reactive state is **interoperable** and the graph is **introspectable**, which is precisely what powers the live dependency graph in the [Playground](https://playground.fluixi.com) and `@fluixi/devtools`. The everyday API (`createSignal` and friends) is almost always what you want, but now you know what's underneath it. --- # Components A component is just a function that returns markup. There is no base class and no lifecycle of re-renders, a component runs **once** to create its DOM, and reactivity keeps it up to date. ```tsx function Greeting(props: { name: string }) { return

    Hello, {props.name}

    ; } ; ``` ## Props are reactive Because a component runs only once, a prop is a live read rather than a value handed over at call time. Read props **where you use them** and updates flow through: ```tsx function Hello(props: { name: string }) { return

    {props.name}

    ; // stays reactive } // const { name } = props; // in plain JavaScript, reads once: see below ``` Destructuring copies the value out at that moment, so `name` stops following the prop. That is ordinary JavaScript, not a rule Fluixi invented. ### Destructuring anyway The compiler rewrites those bindings back into reads, so the plain syntax keeps working, in the parameter list or at the top of the body: ```tsx function Hello({ name, tone = 'calm' }) { return

    {name}

    ; // both stay reactive } function Badge(props) { const { label, ...rest } = props; // rewritten the same way return {label}; } ``` A destructure of `props` that runs once elsewhere in the component's setup, inside an `if` block or sharing its `const` with other names, is left as written and the build warns about it. One inside a callback is fine as it is: it reads the current values each time the callback runs. It compiles to `props.name` at each use, the binding keeps its type, so nothing else about the function changes. This is on by default; `fluixi({ propsDestructure: false })` turns it off, which you want for a package that ships its source for consumers to compile. Aliases, defaults and nested patterns all work, and a default still applies only to `undefined`, exactly as it would in JavaScript. `...rest` becomes the `splitProps` call you would have written: ```tsx function Field({ label, ...rest }) { return ; } ``` `splitProps` carries the remaining props across as getters instead of reading them out, so a signal behind a forwarded prop still reaches the element. Where the compiler can't prove the rewrite is safe it leaves your code exactly as written and says why, a reassigned binding, a computed key, a default it would have to re-run on every read. Those keep the JavaScript meaning they always had. One thing to watch: this is a property of **how the code is compiled**, not of the code itself. If you publish a package that ships its source for consumers to compile, write props the explicit way, a consumer without the option would read them once. Compiled output is fine either way. The [props example](https://github.com/fluixi/core/tree/main/examples/props) has all of it running, and turning the option off in its config is the quickest way to see the difference. ### Which expressions stay live The compiler decides, for each prop and each child written in JSX, whether to pass a value or a read. It wraps the expression in a getter when anything in it can change: a call (`count()`, `t('key')`), a property read (`props.name`, `user.email`), or an operator over one of those. Literals and bare identifiers pass once. ```tsx ``` Negations and other unary operators (`!x()`, `-x()`), and TypeScript's `x()!`, `x() as T` and `x() satisfies T`, count like the call inside them. Before 1.0.0-alpha.109 they were passed once, so `collapsed={!panelOpen()}` kept its first value until the page reloaded; the fix needs no change in your code. An arrow function is a value like any other: `onClose={() => close()}` hands over the function, it does not make the prop live. ## Children `props.children` holds whatever you nest inside a component: ```tsx function Card(props: { children?: any }) { return
    {props.children}
    ; }

    Body

    ; ``` Reading `props.children` runs the code that builds them. Read it once; when the component needs to look at its children (count them, pick some out), resolve them with `readChildren`, which keeps the result in a memo with nested functions resolved and arrays flattened: ```tsx import { readChildren } from '@fluixi/core'; function Tabs(props: { children?: any }) { const items = readChildren(() => props.children); return ; } ``` ## Ids for labels and ARIA `createUniqueId()` gives an id the server render and the browser agree on, for pairing elements: a `
    }>

    Welcome back

    ``` When the children need the value, pass a function; it receives the value, already checked: ```tsx {(u) =>

    Welcome back, {u.name}

    }
    ``` Plain children are built once while the condition stays true. A function child runs again each time `when` becomes a **different** truthy value (a new object), and builds a new branch. ## Switch and Match Several exclusive branches; the first `Match` whose `when` is truthy wins: ```tsx Unknown status

    }>
    ``` ## For A list of objects. The row function runs once per item; when the list changes, rows are added, removed and moved, not rebuilt: ```tsx Nothing to do

    }> {(todo, i) =>
  • {i() + 1}. {todo.title}
  • } ``` By default an item is matched by its object reference. Data refetched from an API arrives as new objects every time, which would rebuild every row; give `by` a key, and the same key keeps its row, its DOM and its focus. With `by`, the item is an accessor, since its contents can change under the same key: ```tsx t.id}> {(todo) =>
  • {todo().title}
  • }
    ``` ## Index A list where the position matters more than the item: primitives, a fixed set of slots, a grid. Each slot is built once, and the item at that position is an accessor that changes: ```tsx {(score, i) => {i + 1}: {score()}} ``` ## Dynamic When the component or the tag itself changes: ```tsx const views = { grid: GridView, list: ListView }; {title()} ``` A new prop updates the current component in place; a new component or tag replaces it. ## ClientOnly A subtree that cannot render on the server (it reads `window`, `localStorage`, the time zone). The server and the hydration render `fallback`; the children are built in the browser right after: ```tsx import { ClientOnly } from '@fluixi/core'; }> ``` ## Portal Renders somewhere else in the document, a dialog or a tooltip, while it stays part of the component that owns it: its context, and its cleanup when that component goes. ```tsx ``` Without `mount` it goes at the end of `document.body`. On the server a portal renders nothing; in the browser its content mounts once the page has hydrated. ## On an element The same branches and lists can sit on an element as attributes, `if`, `else`, `each` and `key`, or on `` when no element should be added. The compiler turns them into the components above. See [Control flow in directives](/v1/en/directives#control-flow). ```tsx
      {(row: Row) =>
    • {row.name}
    • }

    Welcome back

    Sign in ``` On a lowercase tag TypeScript cannot infer the item, so annotate it, or use `` where the type should be inferred. ## Where to use which, and what not to write | You have | Use | |---|---| | one condition | `Show` | | several exclusive cases | `Switch` / `Match` | | a list of objects | `For`, with `by` when the objects are recreated | | primitives or fixed slots | `Index` | | a component or tag chosen at run time | `Dynamic` | | browser-only content | `ClientOnly` | | content placed elsewhere in the page | `Portal` | **Not `cond() && ` for anything with state or cost.** The expression is one reactive insertion: each time it runs again, even while the condition stays true, it disposes `X` and builds it again, cleanups included. ```tsx // ✗ rebuilt whenever n changes, though it stays positive {n() > 0 && } // ✓ built once while the condition holds; the count updates in place 0}> ``` **Not `.map()` for a list that changes.** It rebuilds every row on each change: ```tsx // ✗ every row rebuilt when one is added {todos().map((t) =>
  • {t.title}
  • )} // ✓ only the new row is built t.id}>{(t) =>
  • {t().title}
  • }
    ``` **Not an early `return` in the component body.** It runs once: ```tsx // ✗ decided once: logging in later never shows the dashboard if (!user()) return ; // ✓ }> ``` **Not a callback as `when`.** `when` accepts a function as an accessor and calls it; to test whether a callback was passed, use `when={!!props.onClose}`. ## Under the hood Each control-flow component is a memo over its condition or list. `Show` and `Switch` build a branch under its own owner and dispose that owner when the branch changes. `For` keeps a map from item (or key) to row, and on each change works out the rows to add, remove and move, so DOM nodes for unchanged rows are moved, never recreated; `Index` keeps one row per position and updates the item signal of each. All of them are server-rendered and adopted by hydration in place. Next: **[Lifecycle](/v1/en/lifecycle)**. --- # Lifecycle A component function runs once and never re-renders, so its lifecycle comes down to two moments: when it is in the page, and when it goes. `onMount` and `onCleanup` mark them; `ref` gives you the element in between. ## onMount Runs once, in the browser, after the component's elements are in the page. It never runs during a server render. ```tsx import { onMount } from '@fluixi/core'; function Search() { let input!: HTMLInputElement; onMount(() => input.focus()); return ; } ``` A function returned from `onMount` runs when the component goes, so setup and teardown sit together: ```ts onMount(() => { const observer = new ResizeObserver(([entry]) => width.set(entry.contentRect.width)); observer.observe(panel); return () => observer.disconnect(); }); ``` ## onCleanup Runs when the owning scope is disposed: the component leaves the page, a `` branch closes, a list row is removed. Inside an effect it also runs before each new run. ```tsx import { onCleanup } from '@fluixi/core'; function Clock() { const now = $signal(new Date()); const id = setInterval(() => now.set(new Date()), 1000); onCleanup(() => clearInterval(id)); return ; } ``` `onUnmount` is the same function under another name. ## Refs `ref` hands you the element itself. Assign it to a variable, or pass a function: ```tsx let el!: HTMLInputElement; ; (el = node)} />; ``` The element exists from the moment the component builds it, but it is in the page only once `onMount` runs: measure it, focus it or hand it to a library there. ## A realistic example A dropdown that closes on a click outside it and on Escape. The listeners go on the document while the dropdown is open, and come off when it closes or the component goes: ```tsx function Dropdown(props: { label: string; children?: any }) { const open = $signal(false); let root!: HTMLDivElement; $effect(() => { if (!open()) return; const onPointer = (e: PointerEvent) => !root.contains(e.target as Node) && open.set(false); const onKey = (e: KeyboardEvent) => e.key === 'Escape' && open.set(false); document.addEventListener('pointerdown', onPointer); document.addEventListener('keydown', onKey); onCleanup(() => { document.removeEventListener('pointerdown', onPointer); document.removeEventListener('keydown', onKey); }); }); return (
    {props.children}
    ); } ``` The effect reads `open()` first, so on the server, where the dropdown starts closed, it returns before touching `document`. ## Where to use it, and where not Use `onMount` for work that needs the element in the page or the browser itself: focus, measurement, a third-party widget, reading `localStorage` or the viewport. Use `onCleanup` next to anything that has to be undone: a timer, a listener, a subscription, a widget. **`onMount` does not track.** A signal read inside it subscribes nothing, so it will not run again when that signal changes. Use an effect for work that should follow a value. **Not to load data.** Data loaded in `onMount` starts only after the page is shown, is missing from the server render, and has no loading or error state. Use the route's `routeData` or a [resource](/v1/en/async). **Not as a way around a hydration mismatch, except on purpose.** Setting a signal in `onMount` to a browser-only value (the viewport, a stored preference) is the right way to show it after hydration; the first render, on both sides, uses the default. For a whole subtree that cannot render on the server, `` is clearer. **Every listener and timer needs its `onCleanup`.** Without it, a component that leaves the page keeps running its timers and listeners, and leaks the memory they hold. ## Under the hood Each component runs under an owner, a node in a tree that mirrors the component tree. `onMount` queues its callback on the owner and runs the queue in a microtask after the component is built; `onCleanup` adds a callback to the owner's disposal list. When an owner is disposed (its `` closes, its row is removed, its parent goes), its children are disposed first, then its own cleanups run in reverse order. Next: **[Routing](/v1/en/routing)**. --- # Context A context is a value a component provides and any component below it reads, without passing it through every level as a prop: the current theme, the signed-in user, the tabs a tab belongs to. ```tsx import { createContext, useContext } from '@fluixi/core'; const Theme = createContext<'light' | 'dark'>('light', 'theme'); function App() { return ( ); } function Toolbar() { const theme = useContext(Theme); // 'dark' return ; } ``` `useContext` returns the value of the nearest Provider above the calling component, or the context's default when there is none. The second argument of `createContext` is a name, which devtools show for it. ## Values that change The Provider's value is read once. To share something that changes, provide a signal, or an object of signals, and read it where it is used: ```tsx const Session = createContext<{ user: () => User | null }>(); function Shell(props) { const user = signal(null); return {props.children}; } ``` A component that reads `useContext(Session).user()` follows every change; the Provider itself never re-renders. ## A context that must be provided For a part that only works inside its parent, a tab outside its tabs, a default value would hide the mistake. `requireContext` throws instead: ```ts const tabs = requireContext(Tabs, 'A goes inside .'); ``` ## Providers without JSX `createProvider(context, value, props)` provides from a plain function, for a component that provides and renders its children: ```ts const ThemeProvider = (props) => createProvider(Theme, 'dark', props); ``` An app shell often nests a Provider per context. `composeProviders` writes them as a list, outermost first: ```ts const AppProviders = (props) => composeProviders([[Theme, 'dark'], [Locale, () => locale()], [Session, session]], props); ``` A value may be an accessor, read once. Pass the component's own props in both cases, so its children stay lazy and render inside the Providers. ## Custom elements The same context objects work across [custom elements](/v1/en/web-components): an element reads what a Provider around it gives, and the components an element renders read what the element provides. A server-rendered element hydrates with the context of the app it was rendered in. ## Context or dependency injection Context follows the component tree: a value depends on where you are. For services that do not, an API client, a logger, use [dependency injection](/v1/en/dependency-injection), which resolves by token for the whole app. --- # Web components `@fluixi/web-components` builds standard custom elements with Fluixi's reactivity inside. The element works in any page and any framework, React, Vue, Svelte or none, and in a Fluixi app it renders on the server and hydrates like any other part of the page. ```ts import { defineCustomElement, prop, typedElement } from '@fluixi/web-components'; import { html } from '@fluixi/dom'; import { signal } from '@fluixi/reactive/signal'; const counterProps = { step: prop.number(1), // step="5" or el.step = 5 label: prop.string('Count'), }; export class FxCounter extends typedElement(counterProps) { #count = signal(0); protected override render() { return html` ${() => this.label} ${() => this.#count()} `; } get count() { return this.#count(); } increment() { this.#count.set(this.#count() + this.step); this.emit('change', { value: this.#count() }); } } defineCustomElement('fx-counter', FxCounter); ``` `render` runs once. Each binding in it updates the one node it belongs to when a prop or a signal changes; nothing re-renders. JSX works as well as `` html`` ``. ## Props A prop is a property and the attribute that mirrors it, kept on one signal: `el.step = 5` and `step="5"` land in the same place, and a framework binding and server-rendered HTML agree. | Declaration | Attribute | | --- | --- | | `prop.string(initial)` | as written | | `prop.number(initial)` | parsed; a value that is not a number keeps `initial` | | `prop.boolean(initial)` | present or absent | | `prop.object(initial)` | JSON | | `prop.custom(initial, { fromAttribute, toAttribute })` | your conversion | | `prop.any(initial)` | none: a value only a property can carry, such as a function | Options: `attribute` renames the attribute (the property name lowercased by default) or turns it off with `false`; `reflect: true` writes the property back to the attribute on every change; `equals` decides when a new value is a change. `typedElement(props)` gives the class those props as typed fields. A subclass extends it like any class, spreading the parent's props: ```ts const boundedProps = { ...counterProps, max: prop.number(10) }; export class FxBoundedCounter extends FxCounter { static override props = boundedProps; declare max: number; } ``` ## Events `this.emit(type, detail)` dispatches a `CustomEvent` that bubbles out of the element. List them in an interface so consumers get typed handlers: ```ts export interface CounterEvents { change: { value: number }; } ``` ## Using it in JSX Register the element's types once, and JSX checks its attributes and events like any tag: ```ts declare global { interface HTMLElementTagNameMap { 'fx-counter': FxCounter; } interface JSXCustomElements { 'fx-counter': ElementAttributes; } } ``` ```tsx save(e.detail.value)} /> ``` A function, an object or an array passed as a prop is assigned as a property, never stringified into an attribute. ## Shadow DOM and styles Elements render into the light DOM by default, so page CSS reaches them and server-rendered children stay where they are. Set `static shadow = 'open'` (or attachShadow options such as `{ mode: 'open', delegatesFocus: true }`) for a shadow root, and `static styles` for its CSS: ```ts export class FxTab extends typedElement(tabProps) { static override shadow = 'open' as const; static override styles = `:host { display: contents; } [role=tab] { font: inherit; }`; } ``` Each distinct stylesheet is constructed once and shared by every instance and subclass. A parent meant to be extended declares `static styles: ElementStyles`, and a subclass adds to it with `[super.styles, '...']`. ## Children and named slots without shadow DOM In light DOM there is no `` to project into. The children written between the element's tags are taken out before `render()` runs, and the element places them itself. `this.authoredChildren` holds all of them; `this.slotted(name)` holds those marked `slot="name"`, and `this.slotted()` the ones without a `slot`, text included: ```tsx class FxPanel extends typedElement(panelProps) { protected override render() { return (
    {this.slotted('header')}
    {this.slotted()}
    {this.slotted('footer')}
    ); } } ``` ```html

    Settings

    Changes save as you go.

    ``` A child the element never places is not shown, and Fluixi warns about it in development. Under shadow DOM both stay empty: the browser assigns children to ``s itself. Split a larger element into a container and parts the way a component would (`fx-panel` and `fx-panel-item`), and let the container hand its state to the parts through [context](#context-between-elements) rather than props on each one. ## Context between elements Elements share values the way components do. One provides, any element inside it consumes, and the context objects are those of [Context](/v1/en/context), so an element also reads what a Provider in the app gives. `provideContext` and `consumeContext` take the element first; an element that uses neither carries none of this code: ```ts import { consumeContext, provideContext } from '@fluixi/web-components'; const Tabs = createContext(null, 'tabs'); class FxTabs extends typedElement(tabsProps) { protected override render() { provideContext(this, Tabs, { selected, select }); return html``; } } class FxTab extends typedElement(tabProps) { protected override render() { const tabs = consumeContext(this, Tabs); // an accessor; follows the provider when it arrives // ... } } ``` It follows the community context protocol, so it interoperates with `@lit/context` in both directions. An element defined before its provider picks the value up when the provider announces itself. ## Forms and focus `FormAssociated` makes an element a form control the way `` is: it submits a value, reports validity, follows a disabled `
    `, resets and restores. ```ts class FxRating extends FormAssociated(typedElement(ratingProps)) { select(value: number) { this.value = value; this.setFormValue(String(value)); this.setValidity(value ? {} : { valueMissing: true }, 'Pick a rating.'); } } ``` Page code treats it like any input: `el.form`, `el.checkValidity()`, `new FormData(form)`. For keyboard handling, `rovingFocus` moves focus between items with the arrow keys, Home and End, `trapFocus` keeps it inside a dialog, and `tabbables` and `deepActiveElement` find focusable elements across shadow roots. ## A function instead of a class `defineElement` defines an element from a setup function, a subclass underneath: ```ts defineElement('fx-greeting', ({ props }) => html`

    Hello, ${() => props.name()}

    `, { props: { name: prop.string('world') }, }); ``` The setup receives `props` as accessors, `set`, `dispatch`, `provide`, `consume`, `targets` and `children`. Use the class when the element has public methods or will be extended. ## Server rendering In a Fluixi app, an element used in a page renders on the server like the page around it: its props as attributes, objects as plain JSON, its content in the light DOM. In the browser it adopts that markup instead of building it again, and waits for the app to hydrate so it reads the app's context. Declarative shadow DOM is not emitted yet, so a shadow-root element renders its content on the client. `@fluixi/start` sets this up for you. Elsewhere, two imports turn it on, and an app that leaves them out carries none of that code: `@fluixi/web-components/server` where the server renders, `@fluixi/web-components/hydrate` in the browser entry. ```ts import '@fluixi/web-components/server'; // server entry, before rendering import '@fluixi/web-components/hydrate'; // client entry, before hydrating ``` ## Loading and registration `defineCustomElement(name, constructor)` registers through the browser's registry and skips a name already defined, which matters when standalone bundles each include a shared parent class. `defineWhenUsed(name, load)` registers only once the tag appears in the document, so a page that never uses an expensive element never loads it. --- # Component resolution A capitalised tag with no binding in scope is a name the compiler can look up. Tell it where `Button` lives once, and every template can use ` ); } ``` This is not auto-import in the editor sense; nothing is written into your source. The compiler injects the import while compiling, so the output is exactly what you would have written by hand, and the bundler sees a normal static import. Fluixi already did this for `Show`, `For`, `Portal` and the router components. `resolve` is the same mechanism, opened up. ## Configuring it Rules live on the plugin, because where a component comes from is the same everywhere in a project: ```ts // vite.config.ts import { fluixi } from '@fluixi/vite-plugin'; export default defineConfig({ plugins: [ fluixi({ resolve: [ { components: { Button: '@ui/button', Stack: '@ui/layout' } }, ], }), ], }); ``` A component library ships its own map, so adopting it is one line: ```ts import { uiComponents } from '@fluixi-ui/resolver'; fluixi({ resolve: [uiComponents()] }); ``` ### When the tag and the export differ ```ts resolve: [ { components: { Btn: { module: '@ui/button', export: 'Button' } } }, // `export: 'default'` for a file-per-component layout { components: { Card: { module: './Card.js', export: 'default' } } }, ]; ``` ### Patterns One rule can cover a family. `$1` and friends are substituted from the match: ```ts resolve: [{ match: /^Icon(.+)$/, module: '@/icons/$1' }]; ``` `` resolves to `@/icons/Trash`. Note the limitation below, patterns cannot be declared for TypeScript. ### An import always wins Writing the import yourself shadows the rule. Resolution only fills in names that have no binding in scope, so there is never a conflict to resolve, and moving a component out of the config is safe. ## Telling TypeScript The import only exists after compilation, so without help TypeScript reports `Cannot find name 'Button'` for every resolved tag, the code runs, the editor is unusable. The plugin generates the declarations for you. On dev-server start and on build it writes `fluixi.d.ts` at the project root: ```ts // GENERATED by @fluixi/compiler, do not edit. import * as __ui_button from '@ui/button'; declare global { export import Button = __ui_button.Button; } ``` **Commit this file.** It is what makes a fresh clone type-check before anyone runs the dev server, and it means a CI job that type-checks without building still works. It has to be covered by `include` in `tsconfig.json`, which for the default location means naming it alongside `src`: ```json { "include": ["src", "fluixi.d.ts"] } ``` Scaffolded projects already have that line. If the file lands somewhere TypeScript will not read it, the plugin says so during the build, an ignored file and a missing one produce identical errors, so it is worth being told which one you have. Put it elsewhere, or turn it off, with `globals`: ```ts fluixi({ resolve: [...], globals: 'types/fluixi.d.ts' }); fluixi({ resolve: [...], globals: false }); ``` ### What the generated file leaves out - **Names `lib.dom` already claims.** An ambient `const Text` cannot beat the DOM's own `Text`, so those are skipped and listed in the header, import them explicitly. - **Components from packages you do not depend on.** Declaring one produces an unresolvable import, which under `skipLibCheck` fails silently and degrades the component to `any`, worse than the error it replaced. - **Pattern rules.** A pattern matches unboundedly many names, so there is no list to emit. Those tags compile, but need a hand-written declaration for the editor. ## In the editor `@fluixi/ts-plugin` resolves the same names, so hover, go-to-definition and rename work on a resolved tag exactly as they would on an imported one, including inside `` html`` `` templates, where the tag is only text as far as TypeScript is concerned. Because the declarations use an alias (`export import Button = ...`) rather than a typed constant, hover keeps the real signature and its JSDoc, and go-to-definition lands on the component's source rather than on the generated file. --- # Loading strategies `resolve` says **where** a component comes from. `load:` says **when** its code should be fetched. They are separate because they vary independently. Where `` lives is the same everywhere and belongs in config; whether *this particular usage* should wait for the viewport is a property of the usage. ```tsx {/* eager, entry chunk */} {/* own chunk, on the first interaction with it */} {/* own chunk, desktop only */} {/* own chunk, just before it scrolls in */} ``` No import, no `lazy()`, no wrapper component. The compiler emits the dynamic import and the deferred binding. ## The strategies | Directive | When the module is fetched | | --- | --- | | `load:eager` | Immediately, in the parent chunk. The default. | | `load:idle` | When the browser goes idle. | | `load:visible` | When the element approaches the viewport. | | `load:interaction` | On the first interaction with the component. | | `load:media` | When a media query matches. | | `load:never` | Never, no client code at all. | The server renders a deferred component in full either way. Until its code arrives, the page keeps what the server sent in its place: it shows, but does not respond yet. Once the code loads the component renders and takes over. A `load:media` component whose query never matches keeps the server's content for good. In a page reached by client navigation there is no server content, so the slot stays empty until the code loads; for `load:never`, which has no code in the browser build, it stays empty. ### `load:visible` Takes an optional margin, passed through as the observer's `rootMargin`: ```tsx {/* on intersection */} {/* 200px early */} ``` Prefer the margin. Starting the fetch exactly on intersection means the user watches a blank space while the network works. ### `load:interaction` Fetches on the first interaction with the component: the events are listened for on the HTML the server rendered for it. What the user does there before the code arrives (the click after the `pointerdown`, text typed in a field) is played again on the component once it renders, so the interaction that woke it is not lost. Rendered in the browser instead (a page reached by a client navigation, or an app without server rendering), the component has nothing on the page yet, and the first interaction anywhere on the page starts it. A component wrapped with `deferred()` and given an element as `fallback` listens on that element. Defaults to `pointerdown`, `focusin` and `keydown`, the three that reliably precede a real interaction, keyboard and pointer alike. Name your own to narrow it: ```tsx ``` ### `load:media` The query is required, since there is no sensible default: ```tsx ``` ### `load:never` A statement that the component has no place in the client bundle at all, server-rendered output only. Unlike the others this is not about timing, so it is never collapsed away (below), and pairing it with an eager usage of the same module is reported as the contradiction it is. ## The strategy has to be static `load:` is read at compile time, because it decides how the module is emitted. A runtime value cannot answer that, so a `${...}` hole is rejected rather than silently ignored. ## Deferring nothing is not free If a module is already in the parent chunk, because something else uses it eagerly, then deferring it elsewhere buys nothing and costs a wrapper, a promise and a re-render. The compiler notices and demotes those references back to eager. Collapsing happens per **module**, not per component name: `