FUNSTACK UI

HomeWhyGetting startedConceptsComponentsRoadmap
GitHub

FUNSTACK UI is in beta. Part of the FUNSTACK family with FUNSTACK Router and FUNSTACK Static, which build this site.

Introduction

  • Why FUNSTACK UI
  • Overview
  • Getting started

Concepts

  • Action props
  • Pending & optimistic state
  • Transitions & ViewTransition
  • Suspense
  • Browser-owned state
  • Server Components

Guides

  • Replacing the element (render)
  • Direction and locales
  • Experimental features
  • Next.js App Router
  • React Router framework mode
  • Content Security Policy
  • Using with AI agents

Components

  • Buttons
    • Button
    • Toggle
    • ToggleGroup
    • Toolbar
  • Disclosure
    • Tabs
    • Accordion
    • Collapsible
    • NavigationMenu
  • Overlays
    • Tooltip
    • HoverCard
    • Popover
    • Dialog
    • AlertDialog
    • Drawer
    • Menu
    • Context menu (Menu)
    • Menubar (Menu)
    • Toast
  • Forms
    • Field and Form
    • Checkbox
    • CheckboxGroup
    • RadioGroup
    • Switch
    • Select
    • Combobox
    • MultiSelect
    • Slider
    • NumberField
    • OTPField
    • TextField
  • Output
    • Progress
    • Meter
    • Avatar
  • Layout
    • Separator
    • Scroll areas (recipe)

Resources

  • Roadmap & changelog
  • GitHub ↗

Next.js App Router

FUNSTACK UI needs no setup for the Next.js App Router: import the parts from their subpaths in Server and Client Components, as on Server Components. This page covers the places where Next.js behaviour changes how you use the library. The numbers and messages below were measured in a test app with Next.js 16.4.6 (Turbopack, cacheComponents on) and @funstack/ui 0.1.0-beta.0.

React version

The App Router does not run the react and react-dom packages you installed. It runs the React canary build that Next.js ships inside its own package (next/dist/compiled/react); the Next.js 16 release notes say so. Next.js 16.4.6 ships 19.3.0-canary-278794d7-20261002.

That works. By semver a 19.3.0-canary-… prerelease sorts before 19.3.0, so strictly it is outside the library's >=19.3.0 peer range, but it has every React 19.3 feature the library uses. Install react and react-dom 19.3 or later anyway (create-next-app does): the peer dependency is then satisfied, and tools that import React directly, such as a test runner, use them.

Server Functions

A Server Function is a function marked with "use server" (at the top of its file or of its body): it runs on the server, and the browser calls it over the network. Next.js calls one used for a mutation a Server Action. A Server Function can be passed directly to any action prop, from a Server Component too (see Actions from the server). In Next.js four things follow from how it calls them.

Not during the server render

Next.js refuses a Server Function call while it renders a page on the server. The call throws:

Error: Server Functions cannot be called during initial render. This would create a fetch waterfall. Try to use a Server Component to pass data to Client Components instead.

This matters for content that reads a promise with use() and is visible at first: the selected tab's panel, an item that starts open. It renders on the server, so it cannot start its read with a Server Function. Start that read in a Server Component and pass the promise down as a prop; content shown later loads on the client (next section).

Example: Tabs

The first panel's text comes from the Server Component as a promise. The other panels load theirs when their tab is chosen. The <Suspense> boundary is above the Tabs, so a switch to a panel that is still loading keeps the old panel on screen.

// app/versions/page.tsx: a Server Component
import { Suspense } from "react";
import { connection } from "next/server";
import { getVersionText } from "@/lib/versions";
import { VersionTabs } from "./VersionTabs";

export default function Page() {
  return (
    <Suspense fallback={<p>Loading…</p>}>
      <Versions />
    </Suspense>
  );
}

async function Versions() {
  await connection(); // request-time data (see Cache Components below)
  return <VersionTabs firstText={getVersionText("v3")} />; // a promise, not awaited
}
// app/versions/VersionTabs.tsx
"use client";
import { use } from "react";
import { Tabs } from "@funstack/ui/tabs";
import { loadVersionText } from "@/lib/client-reads"; // fetch, see the next section

function VersionText({ id, initial }: { id: string; initial?: Promise<string> }) {
  return <p>{use(initial ?? loadVersionText(id))}</p>;
}

export function VersionTabs({ firstText }: { firstText: Promise<string> }) {
  return (
    <Tabs.Root defaultValue="v3">
      <Tabs.List aria-label="Versions">
        <Tabs.Tab value="v3">v3</Tabs.Tab>
        <Tabs.Tab value="v2">v2</Tabs.Tab>
      </Tabs.List>
      <Tabs.Panel value="v3"><VersionText id="v3" initial={firstText} /></Tabs.Panel>
      <Tabs.Panel value="v2"><VersionText id="v2" /></Tabs.Panel>
    </Tabs.Root>
  );
}

Reads: fetch a Route Handler

Do not use a Server Function to load data in a client render either (a promise for use() in a panel, a popup or a card). Next.js documents Server Functions for mutations, and calling one updates its router. In the test app this had two effects:

  • React logged Cannot update a component (Router) while rendering a different component for each component that started the call.
  • A Tabs switch whose panel started the call ran its view transition with no transition types. A Panel transition map keyed on fsui-tabs-next then fell through to its default, and the panels did not slide. With the read moved to a Route Handler, the same switch carried fsui-tabs and fsui-tabs-next.

A Route Handler is a Next.js route.ts file that exports a function per HTTP method. Serve client reads from one, and read it with fetch. Keep one promise per key, so that a render that runs again reads the same promise:

// app/api/version/route.ts
import { connection } from "next/server";
import { getVersionText } from "@/lib/versions";

export async function GET(request: Request) {
  await connection(); // never prerendered (see Cache Components below)
  const id = new URL(request.url).searchParams.get("id") ?? "";
  return Response.json({ text: await getVersionText(id) });
}
// lib/client-reads.ts
const texts = new Map<string, Promise<string>>();

export function loadVersionText(id: string): Promise<string> {
  let text = texts.get(id);
  if (text === undefined) {
    text = fetch(`/api/version?id=${encodeURIComponent(id)}`)
      .then((response) => response.json())
      .then((data: { text: string }) => data.text);
    texts.set(id, text);
  }
  return text;
}

Next.js runs them one at a time

Next.js dispatches Server Actions one at a time per client: a call waits until the one before it has finished. React, for its part, holds every transition in the app while any action is pending: every part with an action prop, every controlled part and your own navigations wait. A Server Function passed directly to an action prop returns a promise and is awaited, so its action is pending for as long as Next.js takes to run it, including the time it waits in the queue. An uncontrolled part with no action prop (a menu with no openChangeAction) is not held: it opens while the save runs. Measured in the test app (next dev, Chromium), before parts without an action stopped being held:

  • A Toggle whose Server Function took 300 to 1000 ms, then a click on a menu's Trigger at once: the Trigger showed data-open immediately, and the menu appeared 1350 ms later, when the save settled. A menu with no openChangeAction now opens at once; one with an openChangeAction still waits.
  • Five quick clicks on the Items of a ToggleGroup whose Server Function took about 700 ms: each Item showed its new state at once, and the group carried data-pending for 3.7 s, while Next.js ran the five saves one after another. Every part on the held side waited as long.

Choose per control:

  • Pass the Server Function directly when the UI should wait for it. The control shows data-pending, rolls back if the call fails, and a failure reaches an Error Boundary. Use it for a setting in a menu, a Dialog or AlertDialog action that must succeed before the dialog closes, a form submission.
  • Wrap it as (v) => { void fn(v); } when the UI should not wait: toolbars, toggles the user presses quickly, anything that saves in the background. The action settles at once, so nothing is held; Next.js still runs the calls in order. You give up data-pending, rollback and the Error Boundary: catch the rejection yourself (see Return the promise only when the UI must wait for it).

A Server Component can only pass the Server Function itself, not a function that wraps it. Write the wrapper in a Client Component:

"use client";
import { ToggleGroup } from "@funstack/ui/toggle-group";
import { toast } from "@funstack/ui/toast";
import { saveTextStyles } from "./actions"; // "use server"

export function TextStyles({ initial }: { initial: string[] }) {
  return (
    <ToggleGroup.Root
      aria-label="Text style"
      defaultValue={initial}
      // Not awaited: the action settles at once and holds nothing.
      valueChangeAction={(next, details) => {
        void saveTextStyles(next, details).catch(() => {
          toast({ title: "Could not save the text style", type: "error" });
        });
      }}
    >
      <ToggleGroup.Item value="bold">Bold</ToggleGroup.Item>
      <ToggleGroup.Item value="italic">Italic</ToggleGroup.Item>
    </ToggleGroup.Root>
  );
}

Thrown errors are redacted in production

When a Server Function throws, the action rejects and the error reaches the nearest Error Boundary. Under next dev the boundary receives your message. In a production build the server leaves the message out, and the boundary receives the minified React error #441, whose full text is:

An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.

A thrown error is still right for "something went wrong". For a failure the user should read, return it as a result instead, and wrap the Server Function on the client: show the message, then call details.reject() so that the control rolls back without an Error Boundary.

// app/actions.ts
"use server";
export async function setPinned(id: string, pinned: boolean) {
  if (!(await canPin(id))) return { ok: false, message: "Only owners can pin a note." } as const;
  await db.notes.update(id, { pinned });
  return { ok: true } as const;
}
"use client";
<Toggle
  defaultPressed={note.pinned}
  pressedChangeAction={async (pressed, details) => {
    const result = await setPinned(note.id, pressed);
    if (!result.ok) {
      toast({ title: result.message, type: "error" });
      details.reject(); // roll back, no Error Boundary
    }
  }}
>
  Pin
</Toggle>

A dialog that saves and reports with a toast

A common shape: a dialog with a form whose Server Function saves, a toast that reports the result, and a dialog that stays open with the errors when the save fails. It combines Dialog.Form rendered as Form.Root (Field and Form: in a Dialog), a useActionState inside the Popup, and toast.promise (Toast, with a Toast.Viewport rendered once in your layout). Two facts decide how they fit:

  • The Server Function returns its failure (see above), so the promise fulfils either way. toast.promise shows its error toast only for a rejection: turn a failed result into one.
  • toast.promise with an error option resolves when its promise rejects (the toast is the handler). Its result cannot keep the dialog open. The form state does: a result with errors or error keeps the dialog open, focuses the first errored field or announces the form-level message, and one with neither closes it.
// app/actions.ts
"use server";
export type InviteResult =
  | { ok: true; count: number }
  | { ok: false; errors?: Record<string, string>; error?: string };

export async function invite(formData: FormData): Promise<InviteResult> {
  const emails = String(formData.get("emails") ?? "").split(",").map((s) => s.trim()).filter(Boolean);
  if (emails.length === 0) return { ok: false, errors: { emails: "Enter at least one address." } };
  if (!(await mailer.available())) return { ok: false, error: "Invites are unavailable. Try again." };
  await mailer.invite(emails);
  return { ok: true, count: emails.length };
}
// app/InviteDialog.tsx
"use client";
import { useActionState } from "react";
import { Dialog } from "@funstack/ui/dialog";
import { Field } from "@funstack/ui/field";
import { Form } from "@funstack/ui/form";
import type { FieldErrorValue, FormErrors } from "@funstack/ui/form";
import { toast } from "@funstack/ui/toast";
import { invite } from "./actions";

type State = { errors?: FormErrors; error?: FieldErrorValue };

async function submit(_previous: State, formData: FormData): Promise<State> {
  // Until the result says otherwise: a Server Function that throws keeps the dialog open too.
  let state: State = { error: "The invites could not be sent. Try again." };
  await toast.promise(
    invite(formData).then((result) => {
      if (result.ok) {
        state = {};
        return result;
      }
      state = { errors: result.errors, error: result.error };
      throw new Error(result.error ?? "Check the highlighted field.");
    }),
    {
      pending: { title: "Sending invites…" },
      success: (result) => ({ title: `Invited ${result.count}`, type: "success" }),
      error: (reason) => ({
        title: "Could not send the invites",
        description: reason instanceof Error ? reason.message : undefined,
        type: "error",
      }),
    },
  );
  return state; // {} closes the dialog; errors or error keep it open
}

function InviteForm() {
  // Inside the Popup: each open starts without the last errors.
  const [state, formAction] = useActionState(submit, {});
  return (
    <Dialog.Form action={formAction} render={<Form.Root errors={state.errors} error={state.error} />}>
      <Form.Error />
      <Field.Root name="emails" required>
        <Field.Label>Email addresses</Field.Label>
        <Field.Control />
        <Field.Error />
      </Field.Root>
      <Dialog.Close value="cancel">Cancel</Dialog.Close>
      <Form.Submit value="invite">Invite</Form.Submit>
    </Dialog.Form>
  );
}

export function InviteDialog() {
  return (
    <Dialog.Root defaultOpen={false}>
      <Dialog.Trigger>Invite people</Dialog.Trigger>
      <Dialog.Popup>
        <Dialog.Title>Invite people</Dialog.Title>
        <InviteForm />
      </Dialog.Popup>
    </Dialog.Root>
  );
}

A field error ("Enter at least one address") blocks resubmitting the same value until it is edited; a form-level error allows the retry (Form-level errors). Here both also show an error toast.

Cache Components

create-next-app turns on cacheComponents. The library needs no configuration for it; the rules you meet are Next.js rules:

  • A Server Component that reads data at request time (cookies, or uncached data after await connection() from next/server) must render inside a <Suspense> boundary; Next.js reports an error otherwise.
  • A GET Route Handler is prerendered at build time like a page. One that serves client reads must call await connection() before it reads the request, as in Reads. In the test app, a handler that did not read the request kept answering with its build-time response until it awaited connection().

Content Security Policy

Next.js gives React the nonce as a string, which leaves the library's server-rendered <style> elements without it. Allow them by hash and render CSPProvider without nonce: see What your framework passes to React.