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 ↗

Action props

FUNSTACK UI has no onClick, onChange or onValueChange. Interactive props are actions: callbacks that the component runs inside its own transition and awaits. A change that had already happened when the library heard of it, and that it could not hold, is reported to an on* handler instead.

An action is a function prop that the component calls when the user (or the browser) asks for something, inside a React transition the component starts for it. To dispatch is to start that transition and call the action once; every click, key press or platform change that asks for a change is one dispatch. A transition is React's way to mark an update as non-urgent, so it can keep the current UI on screen while the update is prepared (see Transitions & ViewTransition).

Terms

Settle
An action settles when its promise resolves or rejects (a synchronous action settles when it returns). data-pending stays on until the settle and the render it causes have committed.
Adopt
A controlled parent adopts a dispatched value by setting its controlled prop to it (in the synchronous part of the action, or inside startTransition after an await).
Veto
A controlled parent refuses a change by not adopting the value: when the action settles, the optimistic value snaps back to the committed one. Only a request can be vetoed; a dismissal is a fact and cannot.
Urgent update
A state update outside any transition. React renders it at once, in the event that caused it, and does not hold it back for a pending transition. A setState in an event handler is urgent unless it is wrapped in startTransition.
Form channel
React's own form machinery: <form action>, useFormStatus, useActionState and the automatic reset after a successful action. Independent of a control's change action; see Form actions are a separate channel.

Naming

A controllable state x always comes as a triple: x (controlled), defaultX (uncontrolled initial value) and xChangeAction.

Example: Toggle

A Toggle's state is pressed, so its props are pressed, defaultPressed and pressedChangeAction. Each component page lists its own triple in its props table.

A part that performs one task rather than changing a state (a pure trigger) takes a plain action (Dialog.Close action: run this, then close). A state that the consumer derives and the library only mirrors is a controlled-only prop with no default and no action (Checkbox indeterminate).

undefined always means "uncontrolled"; "nothing selected" is null. Switching between controlled and uncontrolled after mount is not supported (development warning).

Signature

type Action<Args extends readonly unknown[] = []> = (...args: Args) => unknown;

interface ActionDetails {
  /** The DOM event that caused the action, or undefined. */
  readonly event: Event | undefined;
}

/** What an action's details has and a handler's does not. */
interface Rejectable {
  /** Call before the action settles: the request counts as rejected, and nothing is thrown. */
  readonly reject: () => void;
}

type ChangeAction<T, Details extends ActionDetails = ActionDetails> =
  Action<[next: T, details: Details & Rejectable]>;

The first argument is the next value, so the common case stays short. The second is a details object with the native DOM event (not React's synthetic one) and any component-specific fields, such as reason (below) or Dialog's returnValue. An action's details also has reject(). The named details types (SwitchCheckedChangeDetails) do not include it, because handlers share them: a function written apart from the JSX annotates details: SwitchCheckedChangeDetails & Rejectable (both exported from @funstack/ui/types and the root entry). The return type is unknown: return a promise and the component awaits it, return anything else and it is ignored. That means a function that returns data (a Server Function, a fetch) type-checks without wrapping.

Example: Toggle

A change action that returns data, and (on Tabs) one that returns nothing:

<Toggle pressedChangeAction={(pressed) => api.setFavorite(id, pressed)}>Favorite</Toggle>
<Tabs.Root defaultValue="general" valueChangeAction={(tab) => analytics.track(tab)}>...</Tabs.Root>

Typed values

A component whose value is picked from its items is generic over the item value type V: RadioGroup, Menu.RadioGroup, Tabs, Select, ToggleGroup, Accordion, CheckboxGroup, MultiSelect and Combobox. Pass a value of your own union type and the action's next, details.added / removed and the state's value have that type, with no cast:

type Visibility = "public" | "team" | "private";
const [visibility, setVisibility] = useState<Visibility>("team");

// next is Visibility | null: RadioGroup dispatches null when a form reset empties it.
<RadioGroup.Root
  value={visibility}
  valueChangeAction={async (next) => {
    if (next === null) return;
    await saveVisibility(next);
    startTransition(() => setVisibility(next));
  }}
>

// Tabs never dispatches null, so a typed state setter is the action.
<Tabs.Root value={tab} valueChangeAction={setTab}>
WrittenV
value={visibility} or defaultValue={visibility}, a variable of a declared typethat type, without null / undefined
defaultValue="team", value={cond ? "a" : "b"}, defaultValue={["a"]}, defaultValue={null}, defaultValue={[]}string: a literal does not narrow, so next === "private" compiles
only an annotated action: valueChangeAction={(next: Visibility | null) => …}, a Server Function with a typed parameter, a state setterthe parameter's type
<RadioGroup.Root<Visibility> defaultValue="team">Visibility; defaultValue="teem" is then a type error
  • null stays where the component can dispatch it: RadioGroup (a form reset), ToggleGroup and Accordion with exclusive (the item released or closed) and Combobox (Clear). There a setter of a non-null state is a type error; on Tabs, Menu.RadioGroup and Select it fits. TypeScript may report it on value first (Type 'Visibility' is not assignable to type '"private" | null | undefined', with a type it picked from your union); the real message is the one on the action: Type 'null' is not assignable to type 'SetStateAction<Visibility>'. Fix it by handling the null, or by keeping a nullable state:
    // Ignore the null (a form reset to nothing checked):
    <RadioGroup.Root
      value={visibility}
      valueChangeAction={(next) => {
        if (next !== null) setVisibility(next);
      }}
    >
    
    // Or keep it:
    const [visibility, setVisibility] = useState<Visibility | null>("team");
    <RadioGroup.Root value={visibility} valueChangeAction={setVisibility}>
  • Items are checked only when you ask. No type flows between a Root and its children, so <RadioGroup.Item value="anything" /> takes any string. Name the type to check one, or bind it once per file: <RadioGroup.Item<Visibility> value="team" />, const VisibilityItem = RadioGroup.Item<Visibility>.
  • Combobox's allowCustomValue needs string: committed free text is not one of your values, so the prop next to a narrower value and action is a type error.
  • Types only: a value is still a string at runtime (an attribute, a form entry), nothing is checked, and a Server Function receives strings. Validate what it receives as any input. The props types default to string (RadioGroupRootProps is RadioGroupRootProps<string>), so wrappers written against them keep compiling.

Requests and facts: on* handlers

The name of a callback prop is a contract. A prop named action or fooAction receives a request: the component calls it before the change is committed, inside a transition, and awaits it; a rejection, or a controlled parent that does not adopt the value, rolls the UI back. A prop named onFoo is an on* handler: it reports a fact, a change that had already happened when the library heard of it and that the library could not hold.

The test: if the callback rejects, or the parent ignores it, can the library put the UI back without the user noticing? If yes, the change is a request. A form reset or a click before hydration on a checkbox passes the test (the DOM is the optimistic state, and the library restores it on a refusal), so it is a request even though the browser changed the DOM first. A popup the user dismissed with Escape fails it: the user saw it go away.

Most state has only an action. Where both kinds of change exist, a component offers both props, and each component page documents its own handlers. Every on* handler the library defines follows one rule:

  • Called synchronously, in the event that reports the fact, outside any transition: a setState in the body is an urgent update.
  • Not awaited, with no pending or optimistic state: the change has already happened.
  • It may return a promise (an async function, a Server Function). A rejection, like a synchronous throw, goes to reportError, never to an Error Boundary; a throw does not stop the library from updating the component. Nothing warns about a returned promise.
/** Called synchronously, outside any Transition, and not awaited. */
type UrgentChangeHandler<T, Details extends ActionDetails = ActionDetails> =
  (next: T, details: Details) => void;
/** The same for a fact that carries no next value. */
type UrgentHandler<Details extends ActionDetails = ActionDetails> = (details: Details) => void;

Set state directly in a handler, not inside startTransition and not after an await. The advice for actions (wrap the result after an await) does not apply: a handler is not in a transition, and a late update leaves the UI showing the old value for a while.

Example: Popover

An overlay's open state has both kinds of change. Opening, and a close the user asks one of its parts for (a Close button), are requests: openChangeAction. Escape or a click outside is a fact: the browser has already hidden the popup when onOpenChange(false, details) is called from its event. A controlled Root adopts both, with the same setter:

const [open, setOpen] = useState(false);
<Popover.Root open={open} openChangeAction={setOpen} onOpenChange={setOpen}>

See Requests and facts for what each one does to the popup.

Example: Combobox

The text of a controlled input

React requires a controlled text input to update in the same event as the keystroke, so typed text is a fact: when the library hears of it, the DOM already holds it. Combobox keeps the usual pair, inputValue / defaultInputValue, but its callback is a handler, onInputValueChange, not an action. (next) => setText(next) is the whole controlled pattern. What the text drives (a deferred query, an open, a selection) goes back to transitions at once; a fetch whose results should render belongs there, through useDeferredValue of the text.

details.reason

Components that can change for more than one reason say why, with one library-wide vocabulary (the public type ChangeReason):

reasonMeaningdetails.event
"activate"The user acted on one of the component's parts: a click, Enter or Space, focus in automatic activation, a Close button or a form submit.The native click, keydown or focusin event. For checkboxes and radios always the click, including Space and arrow keys.
"platform"The browser changed the state by itself: find-in-page, a form reset, or an interaction before hydration found on mount. Never a direct user interaction (a click, key press or touch).The platform event (beforematch, toggle, reset), or undefined on mount.
"dismiss"The user closed the component without one of its parts: Escape, Android back, an assistive-technology dismiss, a click outside; also a close nobody caused through the component (script, another top-layer element, focus leaving). On an overlay most of these are facts, reported to onOpenChange. Also a Toast's Close part, which only means "go away".The platform's close or toggle event; for Toast the click or keydown.
"timeout"The library's own timer closed the component: a Toast whose duration elapsed. No user interaction, no platform event.undefined

A component uses only the reasons that can happen to it; its page lists them in the description of its change action and of its on* handler. A "platform" dispatch goes through the same action as a user one, so a controlled parent hears about a form reset and decides whether to adopt it. See Browser-owned state.

details.valid

Every value action of a form control (Checkbox, Switch, RadioGroup, CheckboxGroup, Select, MultiSelect, Combobox, TextField, NumberField, Slider, and OTPField's completeAction) says whether the requested value passes constraint validation: the control's native constraints (required, pattern, min / max / step, a group's "at least one") and, inside a Field, the Field's validate, for that value. A server error does not count: it is about a value already submitted. Every reason carries it (a form reset, a value adopted at mount, NumberField's "dismiss"). Handlers and the actions of other components have none.

<TextField
  required
  defaultValue={task.title}
  valueCommitAction={async (next, details) => {
    if (!details.valid) return; // nothing saved
    await saveTitle(next);
  }}
/>

It is information, not a gate: the action is always called, also for an invalid value (the control holds what the user entered, and a Field shows the error). An action that saves checks it. The early return keeps what the user entered in the control and saves nothing; a controlled parent that does not adopt it rolls back instead. One exception, for typed text: in an uncontrolled TextField or NumberField, invalid text is not written at all. It stays a draft, and the saved value stays what a later failed save rolls back to (TextField, NumberField). To put the saved value back instead, return details.reject() (below). It is an ordinary boolean field, so a Server Function passed directly receives it.

What happens on a click

In one transition of its own, the component tags the transition with its transition types, sets the optimistic value, awaits your action, and, when it is uncontrolled and this is still the latest dispatch, commits the new value.

An uncontrolled component with no action prop has nothing to await, so it starts no transition for the change. It writes the new value at once, as an urgent update: the trigger shows it in the same event, and the content region (a panel, a popup) follows in a deferred render. Content that suspends keeps the old UI on screen meanwhile, with data-pending, exactly as in a transition, and a transition prop animates the change with the same types. What the deferred render adds: a pending action elsewhere in the app does not hold it (below). Any action prop, even a synchronous one, puts the change back in the transition above, and so does a part that passes an action of its own (the exceptions are listed below).

Example: Toggle

startTransition(async () => {
  addTransitionType("fsui-toggle");     // plus fsui-toggle-press / -release
  setOptimistic(next);                  // the button flips immediately
  await pressedChangeAction?.(next, details);
  // uncontrolled: commit `next` now, if this is still the latest dispatch
});

What you can rely on:

  • Sync or async. The action is awaited; data-pending stays on until the promise settles and the resulting render has committed (including a Suspense wait).
  • The synchronous part runs during the event. details.event.preventDefault() works there, and a setState there is a transition update.
  • Disabled parts never dispatch for user interaction, and no-op interactions (clicking the tab that is already selected) do not dispatch either. A form reset is not a user interaction with the control: form.reset() resets disabled inputs too, so a disabled control still follows it, with reason: "platform".
  • Parts are never natively disabled while pending. A trigger that changes state sets data-pending and takes every click: a second click is a new intent (below). What a pure trigger does with a second activation while its own action is pending is its whilePending prop: "run" runs it again (the default of a Button), "ignore" drops it and makes the part aria-disabled="true" meanwhile (the default of a Close part; use it on a Save that must not run twice). See A second click while pending.

After an await, wrap state updates yourself

This is a React rule, and the library cannot hide it: a setState that runs after your own await is no longer part of the transition. It is an urgent update and renders at once. What to do with it depends on what the update is:

  • The result of the action (adopting next in controlled mode, the data the action loaded): wrap it in startTransition. It then commits with the end of the action, and content that suspends keeps the old UI on screen.
  • A step that must paint while the action runs (a progress value, "3 of 5 uploaded"): leave it a plain setState. Wrapped in startTransition it is held until every pending action settles, so a progress bar stays at 0 and jumps to the end.
  • A first state, before the first await ("Preparing…", the reverse case): a setState there is in the synchronous part, so it is a transition update and is held as well. Set it with useOptimistic, which shows at once (The first state of a long action).

The example below adopts a result. The upload example on the Button page shows a first state and steps.

Example: Tabs

// Controlled, local state: set it in the synchronous part.
<Tabs.Root value={tab} valueChangeAction={(next) => { setTab(next); }}>

// Controlled, server-backed: adopt the value on success, re-wrapped after the await.
<Tabs.Root
  value={tab}
  valueChangeAction={async (next) => {
    await saveTab(next);
    startTransition(() => setTab(next));
  }}
>

Pending actions hold other transitions

While any async action is pending, React holds every transition update in the app, from any component, until the last pending action has settled. Then it commits them together. This is React's behaviour, not the library's: React cannot tell which action an update belongs to, so it puts all of them in one batch. That includes a router navigation, when the router renders it in a transition.

What this means for the library's parts depends on whether there is anything to await:

  • Not held: an uncontrolled part with no action prop. A Menu, a Tabs, a Combobox listbox, a Collapsible, an Accordion item or a popup with defaultOpen and no openChangeAction writes its value urgently and shows its content in a deferred render (above), so it opens or switches while a save is pending anywhere in the app. So does a Close part, or a closing menu item, without an action of its own. Measured in a test app with a 1.5 s save pending: a Combobox listbox, a Collapsible, a NavigationMenu panel and a Menubar menu each showed within 40 ms, where each waited about 1.4 s before. The same holds for picking a Combobox value, the commit of a Slider or NumberField gesture, and a Menu checkbox or radio item: with no action prop of yours, nothing is awaited.
  • Not held: a part's close on a controlled overlay with no openChangeAction. With open and onOpenChange alone there is nobody to ask, so the library closes the popup in the click and tells onOpenChange(false, { reason: "activate" }) (below). And a value you set urgently yourself wins: an urgent setOpen(false) closes the popup at once, even while a close request of the same overlay is still held.
  • Held: a part with an action prop, synchronous or async, and every controlled part with an action (a controlled overlay with openChangeAction={setOpen}, its Close parts included). The change is a transition, so it waits for every pending action. Its trigger still shows the optimistic value at once, with data-pending; the content region waits. A synchronous action is held too, because the state it sets is a transition update: the part's content waits for that state instead of showing the new value with the old state.
  • Held: your own transitions, such as a router navigation, and state you set inside any action (below).
  • Never held, because the browser performs them and the library holds no state for them: the changes of a component in JS-free mode, and a dismissal.

How long a held change can wait, measured in the same kind of app: a checkbox whose awaited save took 300 to 1200 ms, and while it saved, a part on the held side took up to 1.9 s. Typing in a text input took 20 ms. The time beyond the save was the app's refetch, which the save's action started (see Start refetches after the action).

What waits and what does not

Held until every pending action has settled:

  • Every transition update: a setState inside startTransition or any useTransition, a state update in the synchronous part of an action, and the library's own commits.
  • A transition that a pending action starts after its await joins the same batch. If its render suspends (a refetch), the held updates wait for that data too, even though the action has settled.

Not held:

  • Urgent updates, such as typing into a controlled input.
  • Values set with useOptimistic, which is why a trigger flips at once.
  • The background render of useDeferredValue: content that follows a deferred value updates while an action is pending, and if it suspends, the old content stays without a fallback.

State that other UI reads at once

State you set in an action is a transition update, so it is held too, even when it is purely local and the action awaits nothing. While another action is pending, the part the user acted on shows its optimistic value, but your state still has the old one. Anything that reads your state in the meantime (a count, a button that acts on it) sees the old value until every pending action has settled.

For state that other UI reads at once, keep it in useOptimistic as well. In the action, set the optimistic value and the state. Readers use the optimistic value: it shows at once, and when the held updates commit, the state has the same value.

Example: Checkbox

Row selection in a table, with a bulk action that reads it. With a plain useState set from checkedChangeAction, a user who ticks two rows while a save is pending sees two ticked boxes, but the bulk action reads the selection from before. The selection below goes through useOptimistic:

const [committed, setCommitted] = useState<ReadonlySet<string>>(new Set());
const [selected, setSelected] = useOptimistic(committed);

function select(id: string, checked: boolean) {
  const next = new Set(selected);
  if (checked) next.add(id);
  else next.delete(id);
  setSelected(next); // shown and readable at once
  setCommitted(next); // committed with the held updates
}

<Checkbox
  aria-label={`Select ${user.name}`}
  checked={selected.has(user.id)}
  checkedChangeAction={(checked) => select(user.id, checked)}
/>
<Button action={() => suspendUsers([...selected])}>Suspend selected</Button>

The fallback, if the state must stay a plain useState: set it from an urgent DOM event handler instead of from the action. Some parts merge a handler on their render element with their own, and their Props section says so (a Checkbox merges onChange: render={<input onChange={(event) => setChecked(event.currentTarget.checked)} />}). Then set the state only there: keep checkedChangeAction for other work, such as a save, but do not set the same state in it too. What the fallback gives up:

  • No pending phase: the state changes at once, whether or not an action then runs.
  • No rollback: a rejected action does not undo the state the handler set.
  • No call for a change the library cancels: a read-only Checkbox cancels the click, and no change event fires.

Return the promise only when the UI must wait for it

Return (or await) the save when the UI should wait for it: the component then shows pending state and rolls back if the save fails. For background work, start the promise and return nothing. The action then settles at once, so nothing waits for the save.

What you give up: no data-pending while the save runs, and no rollback. The library never sees the promise, so a rejection does not reach an Error Boundary either: handle it yourself (with .catch), or it becomes an unhandled rejection.

Example: Tabs

// The panel switches immediately; the save runs in the background.
valueChangeAction={(next) => { void saveSelection(next); }}

// The panel switches when the save succeeds; the tab shows pending meanwhile.
valueChangeAction={async (next) => { await saveSelection(next); }}

Start refetches after the action

A refetch started inside the action, after its await, joins the action's batch: every transition held during the save then also waits for the refetched data. Start it once the action has settled instead. A callback queued with setTimeout runs after the component's transition has settled, so the refetch is a transition of its own. Better still, skip the refetch when the component already shows the new value.

Example: Checkbox

// refresh() re-reads the task list; its render suspends until the data arrives.

// The refetch holds every open that waited for the save, until its data loads.
checkedChangeAction={async (checked) => {
  await saveTask(id, checked);
  startTransition(() => refresh());
}}

// Opens held by the save commit when the save settles; the refetch runs after.
checkedChangeAction={async (checked) => {
  await saveTask(id, checked);
  setTimeout(() => startTransition(() => refresh()));
}}

Open your own controlled overlay urgently

An overlay that only its Trigger opens needs nothing: leave it uncontrolled with no openChangeAction, and it is not held (above). When your own code must open it (a keyboard shortcut, a command palette), it is controlled, and a controlled open is held if you set open inside startTransition. Set it with an urgent update instead: an urgent update is not held, so the overlay opens even while a save is pending. The popup reads its open state through a deferred render, so content that suspends keeps the popup closed, with data-pending on the Trigger, until it is ready; no Suspense fallback replaces what is on screen. Parts inside the overlay that are uncontrolled with no action are not held either: in a command palette the Combobox's listbox opens at once, and picking an option with no valueChangeAction closes it and commits the value at once.

Give such an overlay open and onOpenChange, and no openChangeAction. Then its Close parts close it in the click too: there is nobody to ask, so the library closes the popup and tells onOpenChange(false, { reason: "activate" }), where your setOpen adopts it urgently. What that shape costs:

  • No veto: a parent that keeps open at true sees the popup go and come back, as after Escape.
  • The close animates with your CSS exit, not with a <ViewTransition> (it is not a transition).
  • Trigger parts and keys that open do nothing there (a development warning says so): open it from your own handler. With a Trigger, add openChangeAction={setOpen}, and then the Close parts are requests again, held while a save is pending.

The same applies when another part's activation opens, closes or navigates: whatever you set inside that part's action is a transition update and waits. Make the update urgent at its source instead. Where the part merges a click handler on its render element, set the state there and give the part no action (a menu item that opens a dialog). Where only the action knows that the change happened, queue the update out of the action's synchronous part with queueMicrotask: the microtask runs outside the transition (a command palette that closes on a pick). This takes the update out of the action only: a navigation that your router renders in a transition of its own still waits, wherever it starts. So does the close of a controlled overlay with an openChangeAction through its own Close part: that is a request, which runs openChangeAction in the Root's transition. A dismissal (Escape, a click outside) closes it at once, and so does an urgent setOpen(false) of your own, even while that request is held. A recipe whose point is to wait for the action, such as closing a dialog after its save succeeded, keeps the update in the action.

Example: Dialog

In the test app above, this dialog opened in 72 ms while a save was pending; opened inside startTransition, it took up to 2.3 s.

const [open, setOpen] = useState(false);

useEffect(() => {
  const onKeyDown = (event: KeyboardEvent) => {
    if (event.key === "n" && !event.ctrlKey && !event.metaKey && !event.altKey) {
      setOpen(true); // urgent: not held by a pending action
    }
  };
  document.addEventListener("keydown", onKeyDown);
  return () => document.removeEventListener("keydown", onKeyDown);
}, []);

// The handler alone: the Close part and Escape close it at once, too.
<Dialog.Root open={open} onOpenChange={setOpen}>

Keep actions short

An action holds every transition in the app for as long as it is pending (every part with an action prop, every controlled part, your own navigations), so put in it only the work the UI must wait for. Leave out background saves, logging, analytics and prefetching: start them without returning their promise, or after the action has settled. A control that dispatches many times per gesture (a slider drag, a held stepper button, arrow keys that select as they move) needs a cheap action. Where a component also has an action that runs once per gesture, put the save there.

Errors go to Error Boundaries

An action that throws or rejects reaches the nearest Error Boundary above the component that owns the transition (the state owner: usually the Root, or a single-element component such as a Toggle). The library never swallows an error: the rejection of an older action that a newer one superseded goes to reportError instead (see Overlapping actions), and so does a rejection that arrives after the component unmounted (a toast or menu closed while its action ran) or while it is hidden (an <Activity>, a closed overlay with keepMounted, or a Suspense boundary showing its fallback), since React has no render left to deliver it through. A hidden component's error is reported once and does not show the Error Boundary when the component reappears. The optimistic state reverts automatically, and uncontrolled state is only written after success, so a failed action leaves it untouched.

For inline error UI instead, catch inside the action and call details.reject(). Without that call a caught error makes the action resolve, which counts as success: in uncontrolled mode the new value is committed, and a menu item or a toast's Undo closes its container.

Example: Toggle

The left Toggle catches its errors inline and vetoes in controlled mode; the right one lets them reach a boundary.

Show code
ToggleErrors.tsx
"use client";
import { startTransition, useRef, useState } from "react";
import { Toggle } from "@funstack/ui/toggle";
import { DemoErrorBoundary } from "./DemoErrorBoundary.js";
import { fakeSave } from "./fake-api.js";

// Two ways to handle a failing action.
export function ToggleErrors() {
  return (
    <div className="demo-row">
      <ControlledWithInlineError />
      <DemoErrorBoundary>
        <Toggle
          className="demo-toggle"
          pressedChangeAction={(next) => fakeSave(`notify=${next}`, { fail: true })}
        >
          {({ pending }) => (
            <>{pending && <span className="demo-spinner" aria-hidden />}Notify me</>
          )}
        </Toggle>
      </DemoErrorBoundary>
    </div>
  );
}

// Controlled, "update on success": the parent adopts the value only after the save succeeds.
// Every second save fails; the error is caught inside the action, so the Toggle snaps back.
function ControlledWithInlineError() {
  const [pinned, setPinned] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const saves = useRef(0);
  return (
    <span>
      <Toggle
        className="demo-toggle"
        pressed={pinned}
        pressedChangeAction={async (next) => {
          setError(null); // sync prefix: already a Transition update
          try {
            await fakeSave(`pinned=${next}`, { fail: ++saves.current % 2 === 0 });
            // After an await, wrap state updates in startTransition yourself.
            startTransition(() => setPinned(next));
          } catch (e) {
            startTransition(() => setError(e instanceof Error ? e.message : String(e)));
          }
        }}
      >
        {({ pending }) => <>{pending && <span className="demo-spinner" aria-hidden />}Pin</>}
      </Toggle>
      {error && <span className="demo-inline-error"> {error}</span>}
    </span>
  );
}

Handling a failed save without an Error Boundary

An action that catches its own error, shows its own message and then calls details.reject() before it settles is treated as if it had rejected, except that nothing is thrown and nothing is reported:

  • the optimistic value reverts, in uncontrolled mode too (nothing is committed);
  • a part that closes its container after its action does not close it: a Menu.Item leaves the menu open, a Toast.Action keeps its toast, a Close part or AlertDialog.Action keeps the dialog open;
  • an overlay's openChangeAction leaves open as it was;
  • no Error Boundary, no reportError, no data-rejected: the message is yours to render.

Example: Checkbox

Uncontrolled checkboxes that save on change. Tick "Make the next save fail", then a task: the box rolls back and the message appears below the list.

Show code
CheckboxReject.tsx
"use client";
import { startTransition, useRef, useState } from "react";
import { Checkbox } from "@funstack/ui/checkbox";
import { fakeSave } from "./fake-api.js";

const tasks = [
  { id: "t1", title: "Write the release notes", done: true },
  { id: "t2", title: "Review the docs build", done: false },
];

// Uncontrolled checkboxes that handle a failed save themselves: the action catches the error,
// shows its own message and calls `details.reject()`. The box rolls back as if the action had
// rejected, but nothing reaches an Error Boundary.
export function CheckboxReject() {
  const [error, setError] = useState<string | null>(null);
  // Read from a ref: state set inside a pending transition is not visible to a second click.
  const failNext = useRef(false);
  const [failNextShown, setFailNextShown] = useState(false);
  return (
    <>
      <div className="demo-stack">
        {tasks.map((task) => (
          <label key={task.id} className="demo-field">
            <Checkbox
              className="demo-checkbox"
              defaultChecked={task.done}
              checkedChangeAction={async (_next, details) => {
                setError(null);
                const fail = failNext.current;
                failNext.current = false;
                if (fail) setFailNextShown(false);
                try {
                  await fakeSave(`"${task.title}"`, { fail });
                } catch (e) {
                  startTransition(() => setError(e instanceof Error ? e.message : String(e)));
                  details.reject(); // roll back; no Error Boundary
                }
              }}
            />
            {task.title}
          </label>
        ))}
      </div>
      <div className="demo-row demo-options">
        <label className="demo-field">
          <input
            type="checkbox"
            checked={failNextShown}
            onChange={(e) => {
              failNext.current = e.target.checked;
              setFailNextShown(e.target.checked);
            }}
          />
          Make the next save fail
        </label>
      </div>
      {error && (
        <p className="demo-inline-error" role="alert">
          {error}
        </p>
      )}
    </>
  );
}
checkbox.css
/* Checkbox: the input is the box; ::before draws the check (clip-path) or the dash.
   Selectors use [data-checked] rather than :checked because Chromium does not match :checked on
   a box that is both checked and indeterminate. [data-indeterminate] also works before
   hydration, where the DOM property (and :indeterminate) cannot be set yet. */
.demo-checkbox {
  appearance: none;
  flex: none;
  margin: 0;
  inline-size: 1.25em;
  block-size: 1.25em;
  border: 2px solid var(--color-text-secondary);
  border-radius: 0.25em;
  display: inline-grid;
  place-content: center;
  color: var(--color-on-primary);
  cursor: inherit;
  transition:
    background-color 120ms,
    border-color 120ms;
}

.demo-checkbox::before {
  content: "";
  inline-size: 0.7em;
  block-size: 0.7em;
  background: currentColor;
  scale: 0;
  transition: scale 100ms;
  clip-path: polygon(14% 44%, 0 65%, 50% 100%, 100% 16%, 80% 0%, 43% 62%);
}

.demo-checkbox:is([data-checked], [data-indeterminate]) {
  background: var(--color-primary);
  border-color: var(--color-primary);
}

.demo-checkbox[data-checked]::before {
  scale: 1;
}

.demo-checkbox[data-indeterminate]::before {
  scale: 1;
  clip-path: none;
  block-size: 0.18em;
}

.demo-checkbox[data-pending] {
  opacity: 0.6;
}

.demo-checkbox:focus-visible {
  outline: 2px solid var(--color-primary);
  outline-offset: 2px;
}

.demo-checkbox:disabled {
  opacity: 0.5;
}

.demo-checkbox:user-invalid {
  border-color: #dc2626;
}

.demo-nested {
  margin-inline-start: 1.6em;
}

.demo-options {
  margin-top: 16px;
  font-size: 0.9rem;
}

@media (prefers-reduced-motion: reduce) {
  .demo-checkbox,
  .demo-checkbox::before {
    transition: none;
  }
}

The rules:

  • Read when the action settles. A synchronous action calls it before returning, an async one at any point before its promise resolves. Pending does not end early: the part stays data-pending until the action settles.
  • Call it before the action settles. A call afterwards (from a promise the action did not return or await, or a timer) does nothing and logs a development warning. The usual mistake is void save().catch(() => details.reject()): return or await the promise instead.
  • Twice is once, and a throw wins. It cannot be taken back; an action that calls it and then throws anyway is an ordinary rejection and reaches the boundary.
  • Overlaps. It belongs to its own dispatch. On an older action that a newer one superseded it changes nothing on screen; in a set-valued component (CheckboxGroup) that one change is dropped and the others are kept.
  • Controlled mode. The parent's prop stays the truth: for the value, reject() equals not adopting. It is still what keeps a menu, a toast or a dialog open.
  • Actions only. An on* handler reports a fact and has no reject. A form action (Form.Root action, Dialog.Form action) receives FormData and no details; it returns errors instead (Field and Form).

With a Server Function

Like event, reject is not an own property of details, so it is not sent to the server: a Server Function passed directly has no details.reject, and refuses by throwing. To show a message instead, wrap it on the client:

checkedChangeAction={async (next, details) => {
  const result = await setTaskDone(task.id, next); // "use server", returns { ok, message }
  if (!result.ok) {
    toast({ title: result.message });
    details.reject();
  }
}}

reject does not depend on this: async (next, { reject }) => … works. A copy ({ ...details }) has no reject.

With details.valid

The two give the two things an inline-save action can do with an invalid value: keep it in the control and save nothing, or put the saved value back. For typed text the first keeps it as a draft and the second drops the draft.

valueCommitAction={async (next, details) => {
  if (!details.valid) return;                  // the text stays as a draft; the Field shows why
  // or: if (!details.valid) return details.reject();   // the draft is dropped, the saved text is back
  await saveTitle(next);
}}

Overlapping actions: the latest intent wins

React neither cancels nor orders overlapping transitions: two actions started one after the other run at the same time, and either may finish first. The components handle this: the optimistic state always shows the most recent click, and uncontrolled state is committed only for the most recently dispatched action, even if an older one resolves later. The components have no queue and no abort signal; if you need to cancel a request, keep an AbortController in a ref inside your action.

Components whose value is a set of items (CheckboxGroup, and ToggleGroup and Accordion without exclusive) commit each change on its own instead: once every overlapping action has settled, the changes whose actions resolved are applied in the order they were made, and a change whose action rejected is left out. Check A, then B: if saving A fails and saving B succeeds, the uncontrolled group ends with only B checked. B's action still received ["A", "B"] as next, because A was pending when B was clicked, so save details.added and details.removed rather than the whole next.

In controlled mode the committed value is your state, and the library cannot order your updates. A setState after an await runs when that action's promise resolves, so the updates land in completion order: an older response that arrives last overwrites the newer value. Guard the update yourself (keep the latest request's id in a ref and skip a stale one), or queue the calls with useActionState as below.

If your actions must run in order, one after another, or each must build on the result of the one before (reducer-style accumulation), use React's useActionState and call its dispatch function from the component's action. React queues those calls and runs them sequentially, passing each the state the previous one returned. Drive the component in controlled mode from that state:

Example: Toggle

const [pressed, dispatch] = useActionState(async (_previous: boolean, next: boolean) => {
  await api.setFavorite(id, next); // runs only after the previous call has finished
  return next;
}, initial);

<Toggle pressed={pressed} pressedChangeAction={(next) => dispatch(next)}>Favorite</Toggle>

The component stays pending and keeps showing the latest optimistic value until the queue has drained. React's rules for the queue apply: when one call throws, React skips the calls still queued behind it and the error goes to the nearest Error Boundary above the component that called useActionState.

When an older action rejects after a newer one has started, React does not send the error to an Error Boundary: only the latest action's failure is thrown, and the UI keeps showing the latest intent. The library does the same, and also passes the older rejection to the global reportError, as React's standalone startTransition does with a rejection it has nowhere else to send. The error is not lost: it fires the window error event, so error monitoring sees it, and a test runner reports it as an uncaught error.

Server Functions work directly

A Server Function ("use server") can be passed straight to any action prop, from a Server Component or a Client Component, without a client wrapper. The server receives the same arguments, (next, details), with one difference: a DOM event cannot be sent to the server, so details.event is undefined there, and details.reject is missing. Every other field of details (reason, for example) arrives intact.

Example: Toggle

// app/post.tsx: a Server Component
import { Toggle } from "@funstack/ui/toggle";
import { setFavorite } from "./actions"; // "use server"

<Toggle defaultPressed={post.favorited} pressedChangeAction={setFavorite.bind(null, post.id)}>
  Favorite
</Toggle>

details.event is not an ordinary field

To keep details serialisable, event is not an own property of the object, so some operations do not see it. Object.keys(details), spreading and JSON.stringify do not include event; "event" in details and details.event do. structuredClone(details) throws. In tests, assert details.event directly rather than toEqual({ event }). An action's details.reject is served the same way.

Form actions are a separate channel

<form action>, useFormStatus and React's automatic form reset are React's form channel. A control's change action is per control and runs in the control's own transition. The two are independent:

  • A native form control (a Switch, for example) inside <form action={serverFn}> needs no change action: with a name it posts its value like any native input, and useFormStatus().pending covers the submit.
  • A control never folds useFormStatus into its own pending: that would mark every control in the form pending during a submit. Read useFormStatus in your own className function, or style form:has(...).
  • "Autosave on change" is checkedChangeAction={saveSetting}; "submit on change" is checkedChangeAction={() => formRef.current?.requestSubmit()}.
  • A part may observe the form channel for a platform side effect: Dialog.Form closes its dialog once the form action has settled. It watches the form's status and passes your action to <form action> unchanged, instead of wrapping it in a function of its own. That matters for a Server Function: React can only submit a form before JavaScript loads when the action is the Server Function itself; a client wrapper around it would need JavaScript to run.
  • While a form action is pending, a control's transition waits for it, and the reverse: React commits them together.

What about native handlers?

DOM event props that a part does not use itself pass through to the element (an onPointerEnter on a Tab, an onClick on a Tooltip Trigger). They are the platform's API, not the library's. Handlers the part installs itself, in any mode (for example onClick on a Toggle), are removed from its props type: the part's API for that event is its action prop. For the raw event, put a handler on the render element or use ref (Replacing the element).