API Reference
A tour of the most-used What Framework APIs across 14 modules. For the complete export surface, read the bundled type declarations.
Reactivity
The core primitives for building reactive applications.
| Function | Description |
signal(value) | Create a reactive value. Returns getter function with .set(), .peek(), .subscribe() |
computed(fn) | Create a derived value that auto-updates when dependencies change. A function that returns a promise makes an async value: read it in JSX under a <Suspense>; c.pending() says a new value is on its way |
effect(fn) | Run a side effect when dependencies change. Returns dispose function |
batch(fn) | Batch multiple signal writes: the effects they queue run once, synchronously when the outermost batch ends. Returns the callback's value |
untrack(fn) | Read signals without creating subscriptions |
flushSync() | Force all pending effects to run synchronously |
refresh(c) | Fetch an async computed again now; resolves with the new value |
isPending(fn) | Tracked: whether an async value fn reads is fetching a new value |
startTransition(fn) | Keep what fn's writes reach as it was until the async values they made fetch have landed, then commit in one step; resolves at the commit |
useTransition() | React's [isPending, startTransition]; isPending() is an accessor |
useOptimistic(state, update?) | React 19's [optimistic, addOptimistic]; call addOptimistic inside startTransition |
use(x) | A promise's value (the component suspends until it settles), a context's value, or an accessor read untracked |
settled() | Resolves once nothing is queued, fetching or in a transition: act, then await settled(), then read the DOM |
Rendering
Functions for creating and mounting elements.
| Function | Description |
h(tag, props, ...children) | Create an element (advanced/internal). JSX is compiled by the optimizer into direct DOM operations |
mount(element, container) | Render an element tree into the DOM. Returns unmount function |
Fragment({ children }) | Group children without a wrapper element |
html`...` | Tagged template literal for HTML. No build step required |
Control Flow Components
| Component | Description |
<Show when fallback> | Conditionally render children based on a condition |
<For each fallback> | Render a list of an accessor or an array, with fallback shown while the list is empty, on both the compiled and the runtime path. With key={(item) => item.id} each row is built once per key and gets its item as an accessor, item(), that follows an item replaced under the key; without it a row gets the item itself |
<Switch> / <Match when> | Render one of multiple conditions |
<Portal target> | Render children into a different DOM container |
<ErrorBoundary fallback onError> | Catch child render errors, including synchronous throws in reactive JSX children on the server. Without a boundary the synchronous string renderers throw. The streaming engine reports reactive child failures via onError and leaves their regions empty |
<Suspense fallback> | Show the fallback until the async values and lazy components under it have first shown. After that a refresh keeps the content up, and a component that suspends again (lazy(), use(promise)) shows the fallback with the content kept mounted behind it |
memo(Component, areEqual) | No-op pass-through wrapper, kept for React source compatibility. There is no re-render to skip in the run-once model, and areEqual is never called |
lazy(loader) | Code-split a component. Works with Suspense on the client. A failed download's error goes to the error boundary of each render that waited on it; the next render (the boundary's reset) and the next navigation to its route download again, and a loaded component is kept for good. Under SSR renderToStream, renderToStringAsync and renderDocument wait for it; the synchronous renderToString emits the Suspense fallback |
Hooks
React-compatible hooks backed by signals.
| Hook | Description |
useState(initial) | Returns [Signal<T>, setter]. The first element is the signal itself, not a snapshot: read it with count() and it also carries .peek() and .set(). In JSX pass {count} bare so the binding stays live. Components run once, so the setter drives fine-grained DOM effects, it does not re-run the component |
useSignal(initial) | Returns the raw signal for direct signal() and signal.set() access |
useComputed(fn) | Returns a computed signal (read-only derived value) |
useEffect(fn, deps) | Side effect after mount. Return a function from fn to register cleanup; useEffect itself returns nothing. No deps auto-tracks signals, [] runs once, [a, b] re-runs only for the accessors listed ([count], never [count()]: a plain value reports ERR_EFFECT_DEP_NOT_FUNCTION) |
useMemo(fn, deps) | Memoized computation. Returns a Computed<T> accessor, not the value, so call it to read: const total = useMemo(() => a() + b()); total(). deps is accepted for React familiarity and ignored: the computation auto-tracks the signals it reads |
useCallback(fn, deps) | Returns fn unchanged: a component runs once, so the function is already stable. deps is ignored |
useRef(initial) | Mutable ref that doesn't trigger re-renders. Returns { current } |
useReducer(reducer, initial, init) | State with a reducer function. Returns [Signal<S>, dispatch]: the first element is the signal itself, so read it with state() and pass it bare into JSX to keep the binding live. The optional third argument is the lazy initializer, applied to initial once |
useId(prefix) | A unique id string, stable for the component's life (it runs once), as in React |
Lifecycle
| Function | Description |
onMount(fn) | Run code once after component mounts to the DOM |
onCleanup(fn) | Run when the current owner goes: the component unmounts, or the reactive owner (createRoot, a list row, an effect's run) is disposed |
createResource(fetcher, opts) | Reactive data fetching. Returns [data, { loading, error, refetch, mutate }]: data is an async computed (a read before it lands waits under a <Suspense>), loading() and error() are accessors |
Context
| Function | Description |
createContext(default) | Create a context. The context is its own provider: <Ctx value> and <Ctx.Provider value> are the same. Without a default, reading it with no provider reports ERR_CONTEXT_NOT_PROVIDED in development |
useContext(Context) | Access the nearest context value |
Data Fetching
One query cache, from what-framework/data: every key is one entry, an async value in the graph, shared by query() and every hook. Learn more → · DATA.md
| Function | Description |
query(key, fetcher, opts) | The signal-native read: an async value for the entry key names now (a key, or a function of signals returning one). Suspends its <Suspense> on first load, holds a reader while it refetches, keeps the old value with pending() while a new key loads, aborts a key nothing reads, and refresh(q) fetches again. A server render sends it in the data channel under its key, and the hydrating client adopts it with no request. Options: staleTime, gcTime, retry, retryDelay, initialData |
useFetch(url, options) | One URL's JSON from the cache: data(), error(), isLoading(), refetch(), mutate(). url may be a function |
useSWR(key, fetcher, opts) | SWR's shape: data() (the value, fallbackData, or null), error(), isLoading(), isValidating(), mutate(), revalidate(). A null, false or throwing key (or a function returning one) pauses it. Options: dedupingInterval (2000), revalidateOnFocus, revalidateOnReconnect, refreshInterval, fallbackData, keepPreviousData. The fetcher receives the key as written |
useQuery(options) | TanStack Query's shape; never suspends. queryFn gets { queryKey, signal }, with this query's own key. queryKey may be a function of signals, and the query follows it to the new key's entry (a static array is read once). enabled (a boolean, signal or thunk) gates automatic fetching; refetch() is never gated and never answered from the staleTime window. Disabled with nothing cached it reports status() === 'idle'. Options: staleTime, gcTime/cacheTime, select, placeholderData, keepPreviousData, refetchOnWindowFocus, refetchOnReconnect, refetchInterval, retry, retryDelay, callbacks |
useInfiniteQuery(options) | The pages as one cache entry: data() is { pages, pageParams }. On an empty list fetchNextPage()/fetchPreviousPage() fetch the first page from initialPageParam. Invalidating its key refetches page one and replaces the list |
invalidateQueries(keyOrPredicate, opts) | Mark stale and refetch what is shown (inside a transition, the refetch joins it). An array key matches as a prefix on segment boundaries; { exact: true } for that key alone, { hard: true } to empty first, or a predicate that receives each normalized key. A query whose enabled is false is left asleep. Returns a promise of the refetches |
invalidatePath(path) / onRevalidate(path, cb) | Refetch the queries and route data read on path, and run its callbacks. A server action's revalidate calls it inside its transition |
prefetchQuery(key, fetcher, opts) | Fill the cache unless it holds a fresh value; resolves with it |
setQueryData(key, updater) | Land a value in the entry now, for every reader; a fetch in flight for it is dropped |
getQueryData(key) | The cached value (undefined: nothing cached; null: emptied by a hard invalidation) |
clearCache() | Logout: what is in flight is dropped, so no response requested before the clear lands after it. Entries a reader shows stay attached, empty (a hook settles on 'idle', a mounted query() fetches again); the rest are forgotten |
Form state management and validation, imported from what-framework/form. Learn more →
| Function | Description |
useForm(options) | Complete form management: register, unregister, handleSubmit, validate, control, formState (values, errors, error(name), touched, isDirty, isValid, isValidating, isSubmitting, isSubmitted, submitCount, dirtyFields). A field's name is a path: register('vehicles.0.vin') is values.vehicles[0].vin; errors stay keyed by the name |
useFieldArray({ control, name }) | The items of an array field: fields() (each with an id for its row's key), append, prepend, insert, remove, move, swap, update, replace. An item's values, errors and touched state move with it and go when it is removed (Field arrays) |
useField(name, opts) | Individual field control: value(), error(), inputProps(). Both inputProps() and register() bind the input's value ONE WAY today: typing updates form state, but a programmatic setValue() or reset() moves the state without moving the DOM input, so a form that writes its own fields has to set el.value itself |
zodResolver(schema) | Zod validation schema adapter |
yupResolver(schema) | Yup validation schema adapter |
rules.required() | Built-in: required, minLength, maxLength, min, max, pattern, email, url, match, custom |
Input / Textarea / Select | Pre-built components that call register() for you. Like a spread register(), the input they produce is uncontrolled |
Checkbox / Radio | Pre-built toggle components. Checkbox takes its initial checked from the field; Radio keeps checked in sync both ways. Radios in a group share one field holding the selected option, so every <Radio> needs its own value |
ErrorMessage({ name, formState, errors, render }) | Display a field's validation error. It looks the error up in what you hand it, in this order: formState.error(name) (the useForm() shape), then formState.errors[name], then errors[name] (an object or an accessor). There is no form-context lookup, so ErrorMessage({ name }) on its own resolves to null and renders nothing even when the field has an error. It reads the error inside a reactive thunk of its own, so the message appears, changes and goes away with the error. Default output is <span class="what-error" role="alert">; render({ message, type }) replaces it |
Stores
Global state management. Learn more →
| Function | Description |
createStore(definition) | Reactive store from a flat definition object: plain values become state, derived(state => ...) functions become computeds, any other function becomes an action bound to the state proxy. Returns a useStore() hook |
derived(fn) | Mark a function as computed inside createStore |
Animation
Physics and time-based animation primitives, imported from what-framework/motion. Learn more →
| Function | Description |
spring(initial, opts) | Physics-based spring. Options: stiffness, damping, mass, precision |
tween(from, to, opts) | Time-based easing. Options: duration, easing, onUpdate, onComplete |
easings | Built-in: linear, easeInQuad, easeOutQuad, easeInOutCubic, easeOutBounce, etc. |
useTween(opts) | Eased 0..1 progress: isTransitioning(), progress(), start() |
useGesture(el, handlers) | Multi-touch: onDragStart, onDrag, onDragEnd, onPinch, onSwipe, onTap, onLongPress, plus a boolean preventDefault. Returns the live gesture state: isDragging, currentX, currentY, deltaX, deltaY, velocity as signals (startX/startY are plain numbers rewritten at gesture start) |
useAnimatedValue(initial) | React Native-like: spring(), timing(), interpolate() |
createTransitionClasses(name) | CSS transition class name generator |
cssTransition(el, name, type, ms) | Drive one of those class sets on an element: start class, forced reflow, active class, and after ms the done class. Returns a promise that resolves once the done class has landed |
Accessibility
Focus management, ARIA helpers, and keyboard navigation, imported from what-framework/a11y. useId is a hook on the root entry. Learn more →
| Function | Description |
useFocus() | Track focused element: current(), focus(el), blur() |
useFocusRestore() | Capture and restore focus from trigger elements |
useFocusTrap(ref) | Trap focus in container: activate(), deactivate() |
FocusTrap({ active }) | Component wrapper that traps focus |
announce(msg, opts) | Screen reader announcement: priority, timeout |
useAriaExpanded() | Toggle expanded state: buttonProps(), panelProps(). Both return accessor-valued props, so the documented <button {...buttonProps()}> spread keeps aria-expanded in sync as the state changes |
useAriaSelected() | Selection state: itemProps(value), accessor-valued like the rest |
useAriaChecked() | Checkbox state: checkboxProps(), accessor-valued. It also sets role="checkbox", and whichever role is applied LAST wins. On the h() path that is object order: { ...checkboxProps(), role: 'switch' } comes out a switch, { role: 'switch', ...checkboxProps() } comes out a checkbox. In compiled JSX a LITERAL attribute is baked into the cloned template and the spread runs over it afterwards, so neither <div {...checkboxProps()} role="switch"> nor <div role="switch" {...checkboxProps()}> is a switch; a dynamic role={r} written after the spread compiles to a setProp that runs after it and does win |
useRovingTabIndex(count, opts) | Keyboard navigation: getItemProps(i), containerProps(overrides), focusItem(i), setFocusIndex(i), focusIndex(). Arrow/Home/End move real DOM focus and keep exactly one item tabbable. No container role is emitted, pass your own per hook ({ role: 'toolbar' }) or per call (containerProps({ role: 'toolbar' })) |
SkipLink / VisuallyHidden | Skip navigation and screen-reader-only content |
useIds() / useDescribedBy() / useLabelledBy() | Unique IDs and ARIA attribute linking |
Keys / onKey() / onKeys() | Keyboard event constants and handlers |
DOM Scheduling
Imported from what-framework/dom.
| Function | Description |
scheduleRead(fn) | Queue DOM read. Reads run before writes. Returns cancel function |
scheduleWrite(fn) | Queue DOM write. Returns cancel function |
measure(fn) | Promise-based read: await measure(() => el.offsetHeight) |
mutate(fn) | Promise-based write: await mutate(() => { el.style.height = '100px' }) |
nextFrame() | Promise resolving on next animation frame |
onResize(el, cb) | ResizeObserver helper. Returns unobserve function |
onIntersect(el, cb, opts) | IntersectionObserver helper. Returns disconnect function |
smoothScrollTo(el, opts) | Smooth scroll with easing |
Head Management
| Function | Description |
<Head title meta link> | Set document head tags from any component, through the title, meta and link props or <title>, <meta> and <link> children. Auto-deduplicates. On the server the tags go into the render context's head sink, and renderToString returns the body only: use renderToStringWithHead or renderDocument to get them out |
clearHead() | Remove all What-managed head tags (what-framework/dom) |
Helpers & Utilities
Imported from what-framework/dom.
| Function | Description |
cls(...args) | Conditional class builder: cls('btn', { active: true }) |
style(obj) | Convert style object to CSS string (for SSR) |
debounce(fn, ms) | Debounce function calls |
throttle(fn, ms) | Throttle function calls |
useMediaQuery(query) | Reactive media query matching. Returns signal |
useLocalStorage(key, init) | Synced localStorage signal |
useClickOutside(ref, handler) | Detect clicks outside element |
Server-Side Rendering
From what-framework/server, except hydrate, which is the client half and comes from what-framework. Learn more →
An element below can come from h(), the automatic JSX runtime, or what-compiler's server target
The What Vite plugin compiles every module it transforms for the server with what-compiler's server target (generate: "ssr" on the Babel plugin), which lowers JSX to string templates these renderers accept; JSX compiled for the client builds DOM and is refused in a server build (ERR_COMPILED_JSX_IN_SSR). hydrate() adopts the server DOM for an h() tree, and for compiled JSX built with what-compiler's hydratable option, which the Vite plugin turns on (hydratable: 'auto') for a project that renders on the server; JSX compiled without it is rendered again on the client and reported once as an ERR_HYDRATION_MISMATCH of kind not-hydratable.
| Function | Description |
renderToString(element) | Synchronous render to HTML string. Body only: any <Head> tags are dropped |
renderToStringWithHead(element) | Same render, returning { body, head } with the collected head as HTML |
renderToHydratableString(element) | Render with hydration markers so the client can reuse the server DOM |
renderToStringAsync(element, ctx?, options?) | The settled page as one string. Renders on the streaming engine and waits for everything a stream waits for: a resource inside or outside a <Suspense>, an async component, a lazy() component. Returns { body, head, loaderData, resources, owned, ctx }: keyed resources are in resources, a resource with no key is in owned, by owner. Rejects with the error that failed the render; options.onError receives the errors the render contains |
renderToStream(element, options?) | Streaming SSR, shell first: returns { shellReady, allReady, response, pipe, readable, abort }, also async-iterable. Each <Suspense> boundary follows when its data is ready |
renderDocument(pageModule, reqCtx, opts) | The full-stack entry: runs the page's loader, renders through renderToStringAsync, and returns a complete HTML document with the collected head and one <script id="__what_data"> hydration payload (loaderData is null there when the module has no loader). pageModule may be { default, loader } or a bare component, and reqCtx.params are spread onto it as props beside loaderData. Because it goes through renderToStringAsync, the page it returns is settled: resources, async components and lazy() components included. Options: clientEntry (the only thing that emits a client <script type="module">), lang, bodyClass, head, csrfToken |
generateStaticPage(page, data) | Build-time HTML for a definePage() config. The page component renders inside a component frame, so hooks in its own body (useState, useEffect, onMount, a root Context.Provider) work |
hydrate(element, container, { onHydrationError }?) | Client counterpart to mount(): adopts the server-rendered DOM (no node created where it matches, nothing the server sent fetched again) and returns the unmount function. A mismatch reports ERR_HYDRATION_MISMATCH in development and calls onHydrationError in every build, and only the differing part is rendered again |
definePage(config) | Page config: mode (static/server/client/hybrid), title, meta, islands |
server(Component) | Mark component as server-only (no JS shipped) |
Server Actions
From what-framework/server.
| Function | Description |
action(fn, options) | Define a server action. On the client a call is a transition (it joins one already running) that posts to the action endpoint, then revalidates inside it, and resolves once the refetches have landed. Options: id, onSuccess, onError, revalidate (paths: purged on the server, refetched through invalidatePath on the client), invalidates (query keys refetched on the client), revalidateTags, timeout (client fetch timeout in ms, default 30000) |
Form | <Form action={serverActionOrDispatch} redirect?>: a real form that posts without JavaScript, and on a mounted page runs the action as a transition that useFormStatus() reads |
useOptimistic(state, update?) | The root entry's useOptimistic, re-exported: React 19's [optimistic, addOptimistic], where optimistic() is an accessor. Call addOptimistic(value) inside startTransition; the overlay drops when that transition commits, or alone when its action rejects |
generateCsrfToken() | Generate CSRF token for server actions |
Router
From what-framework/router.
| Function | Description |
Router({ routes, fallback }) | Main router component with route config array |
Link({ href, activeClass }) | Navigation link with automatic active class |
navigate(to, opts) | Programmatic navigation. Options: replace, state, transition |
useRoute() | Reactive route state: path(), params(), query(), hash() |
guard(check, fallback) | Route guard HOC for auth/permissions |
defineRoutes(config) | Convert route config object to route array |
Redirect({ to }) | Redirect component |
enableScrollRestoration() | Restore scroll position on navigation |
Quick Reference
import {
signal, computed, effect, batch, untrack, flushSync,
refresh, isPending, startTransition, useTransition, useOptimistic, use, settled,
useActionState, useFormStatus,
h, mount, hydrate, Fragment, html,
Show, For, Switch, Match, Portal, ErrorBoundary, Suspense,
memo, lazy,
useState, useSignal, useComputed, useEffect, useMemo,
useCallback, useRef, useReducer, useId,
onMount, onCleanup, createResource,
createContext, useContext,
createStore, derived,
Head,
} from 'what-framework';
import {
clearHead, cls, style, debounce, throttle, useMediaQuery,
useLocalStorage, useClickOutside, scheduleRead, scheduleWrite,
} from 'what-framework/dom';
import {
query, useFetch, useSWR, useQuery, useInfiniteQuery,
invalidateQueries, invalidatePath, onRevalidate,
prefetchQuery, setQueryData, getQueryData, clearCache,
} from 'what-framework/data';
import {
useForm, useFieldArray, useField, rules, zodResolver, yupResolver,
simpleResolver, Input, Textarea, Select, Checkbox, Radio,
ErrorMessage,
} from 'what-framework/form';
import {
spring, tween, easings, useTween, useGesture, useAnimatedValue,
} from 'what-framework/motion';
import {
useFocus, useFocusRestore, useFocusTrap, FocusTrap, announce,
announceAssertive, LiveRegion, useAriaExpanded,
useAriaSelected, useAriaChecked, useRovingTabIndex, SkipLink,
VisuallyHidden, useDescribedBy, useLabelledBy, Keys, onKey,
onKeys,
} from 'what-framework/a11y';
import {
Router, Link, navigate, useRoute,
guard, defineRoutes, Redirect,
} from 'what-framework/router';
import {
renderToString, renderToStringWithHead,
renderToHydratableString, renderToStringAsync,
renderToStream, renderDocument, generateStaticPage,
definePage, server,
action, Form,
generateCsrfToken,
} from 'what-framework/server';