@molecule/app-react-native

Framework · framework · App (browser) · v5.0.0 · Apache-2.0

React Native framework bindings for molecule.dev

npm install @molecule/app-react-native

npm · Source on GitHub

How it works

@molecule/app-react-native adapts the @molecule/* cores to the framework framework on the app (browser) side.

import { MoleculeProvider, useAuth, useAppState, useSafeArea } from '@molecule/app-react-native'
import { SafeAreaProvider } from 'react-native-safe-area-context'
import { View } from 'react-native'
import { provider as stateProvider } from '@molecule/app-state-zustand'
import { createJWTAuthClient } from '@molecule/app-auth'

const authClient = createJWTAuthClient({ baseURL: 'https://api.example.com' })

function Shell() {
  const { isAuthenticated } = useAuth()
  const { isActive } = useAppState()
  const insets = useSafeArea()
  return (
    <View style={{ paddingTop: insets.top }}>{isAuthenticated && isActive ? <View /> : null}</View>
  )
}

function App() {
  return (
    <SafeAreaProvider>
      <MoleculeProvider state={stateProvider} auth={authClient}>
        <Shell />
      </MoleculeProvider>
    </SafeAreaProvider>
  )
}

Works with: @molecule/app-react

Reference

React Native framework bindings for molecule.dev.

Re-exports the core hooks and providers from @molecule/app-react (they are pure React — no DOM dependency) and adds RN-specific hooks: useAppState (foreground/background), useBackHandler (Android back button), useKeyboardHeight, and useSafeArea. Use useLinkRouter for a link that can open an external URL without a router.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { MoleculeProvider, useAuth, useAppState, useSafeArea } from '@molecule/app-react-native'
import { SafeAreaProvider } from 'react-native-safe-area-context'
import { View } from 'react-native'
import { provider as stateProvider } from '@molecule/app-state-zustand'
import { createJWTAuthClient } from '@molecule/app-auth'

const authClient = createJWTAuthClient({ baseURL: 'https://api.example.com' })

function Shell() {
  const { isAuthenticated } = useAuth()
  const { isActive } = useAppState()
  const insets = useSafeArea()
  return (
    <View style={{ paddingTop: insets.top }}>{isAuthenticated && isActive ? <View /> : null}</View>
  )
}

function App() {
  return (
    <SafeAreaProvider>
      <MoleculeProvider state={stateProvider} auth={authClient}>
        <Shell />
      </MoleculeProvider>
    </SafeAreaProvider>
  )
}

Type

framework

Installation

npm install @molecule/app-react-native @molecule/app-react react

API

Interfaces

AuthState

Reactive authentication state snapshot (initialized, authenticated, user, loading, and error).

interface AuthState<T = UserProfile> {
  /**
   * The session's state as one value — render from this instead of combining
   * `initialized`/`authenticated`/`loading`. `'loading'` is undecided, so wait
   * and redirect only on `'unauthenticated'`; `'unavailable'` keeps the candidate
   * for retry and can have a null profile. A restore failure other than 401/403
   * never signs out. See `AuthStatus`.
   */
  status: AuthStatus

  /**
   * Whether auth state has been initialized.
   */
  initialized: boolean

  /**
   * Whether the client has an authenticated session. This is not a server
   * confirmation flag: during `'unavailable'` it can be false for a retained
   * token/cookie-only candidate with no cached profile. Use `status` for redirects.
   */
  authenticated: boolean

  /**
   * Current user, or null when none is cached. In particular, an `'unavailable'`
   * token/cookie-only restore has a retained candidate but no profile yet.
   */
  user: T | null

  /**
   * Whether an auth operation is in progress.
   */
  loading: boolean

  /**
   * Last auth error (if any).
   */
  error: string | null
}

AuthClient

Auth client interface that all auth bond packages must implement. Provides login/logout/register flows, token management, profile updates, and auth state subscription.

interface AuthClient<
  T = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
> {
  /**
   * Returns the current authentication state snapshot.
   *
   * READING the state starts the client's one session restore when nobody has called
   * `initialize` yet — lazily and exactly once, sharing the promise an explicit
   * `initialize()` returns. A hook (`useAuth()`), a subscriber, `isAuthenticated()` and
   * `getUser()` are reads too, so a client whose entry file dropped the template's
   * `authClient.initialize()` line still restores instead of reporting `'loading'`
   * forever.
   */
  getState(): AuthState<T>

  /**
   * Returns whether the user is currently authenticated.
   */
  isAuthenticated(): boolean

  /**
   * Gets the current user.
   */
  getUser(): T | null

  /**
   * Optional ownership marker for the current session. Compare values only within
   * this client: replacing or ending a session changes it, including re-adopting
   * the same token and user. Profile updates and same-session refreshes keep it.
   * Consumers can use it to discard stale async work without treating editable
   * user fields as an immutable account identifier. Providers without this
   * capability require the consumer's own stable identity check.
   */
  getSessionRevision?(): number

  /** Updates the cached user object (state + persistent storage) without hitting the network. */
  setUser(user: T | null): void

  /**
   * Gets the current access token.
   */
  getAccessToken(): string | null

  /**
   * Stores the access token in the configured token storage adapter (in a
   * browser, Web Storage; `'memory'` where no browser store exists). Use this
   * to seed the token after an out-of-band exchange (e.g. the OAuth
   * code→token redirect) instead of writing to `localStorage` directly,
   * which would violate the storage contract and make a stored bearer token
   * JS-readable (XSS-exfiltratable). Pass `null` to clear it.
   *
   * Passing `null` does not by itself sign a signed-in client out: use
   * `logout` to end a session, or `setUser` with `null` for
   * local-only sign-out. A non-null token on a client that is not signed in is
   * the first or second half of the app's own sign-in pair: together with
   * `setUser` it adopts the session (see there). Prefer `setSession`
   * with the token and user, or `login` / `register` for a
   * credential exchange.
   */
  setAccessToken(token: string | null): void

  /**
   * Adopts a session an out-of-band exchange already established: stores the
   * access token (and the refresh token when given), caches the user, and
   * sets the COMPLETE state — `initialized`, `authenticated`, `status:
   * 'authenticated'`, no error — in one update, with one subscriber
   * notification. Every hook reading the shared client sees the user as
   * signed in immediately.
   *
   * This is the way to seed an OAuth/custom sign-in. The field-setter pair
   * (`setAccessToken` then `setUser`, or the reverse) on a client
   * that is not signed in adopts the session the same way.
   */
  setSession(session: AuthSessionSeed<T>): void

  /**
   * Gets the refresh token.
   */
  getRefreshToken(): string | null

  /**
   * Logs in with credentials.
   */
  login(credentials: LoginCredentials): Promise<AuthResult<T>>

  /**
   * Logs out the current user. The server request is best-effort: a missing
   * logout route (404), any other HTTP failure, or a network error never makes
   * this method reject. It always clears the access token, refresh token and
   * cached user, stops automatic refresh, and publishes one settled
   * `authenticated: false`, `status: 'unauthenticated'` transition. Every pending
   * session operation loses ownership; a persistent marker prevents reload from
   * restoring an older session, and late credentials are revoked best-effort.
   *
   * When the API has no logout route, set `AuthClientConfigOptions.logoutEndpoint`
   * to `null` (or `''`) to skip the request. Local sign-out still happens.
   */
  logout(): Promise<void>

  /**
   * Registers a new user. Accepts the base fields plus the app's own fields
   * (`TRegister`) at the top level — see `RegisterData`.
   */
  register(data: RegisterData<TRegister>): Promise<AuthResult<T>>

  /**
   * Exchanges a stored refresh token, or re-reads `currentUserEndpoint` with the
   * existing access token/session cookie when the API has no refresh credential.
   * That fallback maps, stores and publishes the server user without renewing
   * the access token. Failures reject. A 401/403 ends the session, as does an
   * additional `AuthClientConfigOptions.currentUserRejectionStatuses`
   * code from the fallback. Transient failures retain it as unavailable. Use `updateProfile` for a profile
   * save, or `setUser` with the canonical row from an app-owned mutation.
   */
  refresh(): Promise<AuthResult<T>>

  /**
   * Requests a password reset.
   */
  requestPasswordReset(data: PasswordResetRequest): Promise<void>

  /**
   * Confirms a password reset.
   */
  confirmPasswordReset(data: PasswordResetConfirm): Promise<void>

  /**
   * Updates the current user's profile.
   * Returns the saved profile: the answer applied onto the signed-in user field
   * by field, with or without an `id` — a field it carries replaces the value
   * (`null` clears it), one it omits or leaves `undefined` is kept, so a field
   * cleared by omission must arrive as `null`. A non-object answer is returned
   * as it came. An answer for a replaced or ended session leaves the current one
   * untouched.
   */
  updateProfile(data: Partial<T>): Promise<T>

  /**
   * Changes the current user's password.
   */
  changePassword(oldPassword: string, newPassword: string): Promise<void>

  /** Initializes auth state (e.g., from stored tokens). */
  initialize(): Promise<void>

  /** Re-checks a restored session against the server, in the background — the boot-time validation an app with a stored token needs when a revoked or expired token… */
  validateSession?(): Promise<void>

  /** Resolves when the session restore started by `initialize()` has settled — the point after which the client knows whether this visitor is signed in. */
  whenRestored?(): Promise<void>

  /**
   * Subscribes to auth state changes.
   */
  subscribe(callback: (state: AuthState<T>) => void): () => void

  /**
   * Subscribes to auth state changes (alias for subscribe).
   */
  onAuthChange(callback: (state: AuthState<T>) => void): () => void

  /**
   * Gets the current access token (alias for getAccessToken).
   */
  getToken?(): string | null

  /**
   * Adds an auth event listener.
   *
   * The listener is typed by this client's profile: one signature,
   * `AuthEventListener<T>`, so an inline arrow is contextually typed and `event`
   * is never implicitly `any`. A client whose profile extends
   * `UserProfile` also accepts a default `AuthEventListener`: when
   * `T` extends `UserProfile`, `AuthEvent<T>` is assignable to
   * `AuthEvent<UserProfile>`, so a listener that takes the wider default event
   * accepts every event this client emits and keeps compiling. (`UserProfile`
   * is the wider type here — it has fewer required fields — and the assignable
   * direction runs from the client's `AuthEvent<T>` to the listener's
   * `AuthEvent<UserProfile>`.) A profile that does not extend `UserProfile`
   * (no `id`) rejects the default listener: an `AuthEvent<UserProfile>` would
   * promise an `id` the runtime user does not have, and the narrower-typed
   * event is not assignable to it.
   */
  addEventListener(listener: AuthEventListener<T>): () => void

  /**
   * Destroys the auth client.
   */
  destroy(): void
}

(The 4 longest member comments are shortened to their first sentence to fit; the full declaration is in node_modules/@molecule/app-auth/dist/types.d.ts.)

FormController

Form controller interface.

All form providers must implement this interface.

interface FormController<T extends FormValuesConstraint<T> = Record<string, unknown>> {
  /**
   * Gets the current form state.
   */
  getState(): FormState<T>

  /**
   * Gets the value of a specific field.
   */
  getValue(name: string): unknown
  getValue<K extends keyof T>(name: K): T[K]

  /**
   * Gets all form values.
   */
  getValues(): T

  /**
   * Sets the value of a specific field.
   */
  setValue(
    name: string,
    value: unknown,
    options?: { shouldValidate?: boolean; shouldDirty?: boolean; shouldTouch?: boolean },
  ): void

  /**
   * Sets multiple values at once.
   */
  setValues(values: Partial<T>, options?: { shouldValidate?: boolean }): void

  /**
   * Gets the error for a specific field.
   */
  getError(name: string): string | undefined

  /**
   * Sets the error for a specific field.
   */
  setError(name: string, error: string | undefined): void

  /**
   * Clears the error for a specific field.
   */
  clearError<K extends keyof T>(name: K): void

  /**
   * Clears all errors.
   */
  clearErrors(): void

  /**
   * Gets the field state for a specific field.
   */
  getFieldState<K extends keyof T>(name: K): FieldState<T[K]>

  /**
   * Registers a field for form management. A `defaultValue` that fills an
   * empty field is announced to subscribers once, in a microtask, so a field
   * registered during a render does not update other components mid-render.
   */
  register(nameOrOptions: string | RegisterOptions, options?: RegisterOptions): FieldRegistration

  /**
   * Unregisters a field.
   */
  unregister(name: string): void

  /**
   * Validates a specific field.
   */
  validateField<K extends keyof T>(name: K): Promise<boolean>

  /**
   * Validates all fields.
   */
  validate(): Promise<boolean>

  /**
   * Resets the form and clears errors, touched fields and submission state.
   *
   * With no argument it restores the current baseline — the initial
   * `defaultValues`, or the values a previous `reset(values)` established.
   * Passing `values` merges them over the current baseline and makes the
   * result the new baseline, so a form reset to freshly loaded or saved data
   * reads clean (`isDirty === false`). A changed non-null `id` replaces the
   * record and cancels a pending submit.
   */
  reset(values?: Partial<T>): void

  /**
   * Applies externally loaded values without clearing submission state.
   *
   * The new clean baseline is the original `defaultValues` plus this latest
   * record, never a merge of earlier records. With `keepDirtyValues`, edited
   * fields retain their values while pristine fields take the loaded values.
   * A changed non-null `id` still replaces the record and cancels a pending
   * submit. Equal-content baselines cause no update. `keepOmittedValues` opts
   * into incremental top-level field fills using the current clean baseline.
   */
  updateValues(values: Partial<T>, resetOptions?: FormUpdateOptions): void

  /**
   * Handles form submission.
   */
  handleSubmit(
    onSubmit: (values: T) => void | Promise<void>,
    onError?: (errors: Partial<Record<keyof T, string>>) => void,
  ): (event?: { preventDefault?: () => void }) => Promise<void>

  /**
   * Sets focus to a field.
   */
  setFocus(name: keyof T): void

  /**
   * Subscribes to form state changes.
   */
  subscribe(callback: (state: FormState<T>) => void): () => void

  /**
   * Destroys the form controller.
   */
  destroy(): void
}

FormResetOptions

Options controlling how externally supplied values replace a form's baseline.

interface FormResetOptions {
  /**
   * Keep fields whose current value differs from their baseline when `values`
   * changes. Pristine fields still take the new values. False by default, so a
   * new record can replace edits from the previous record.
   */
  keepDirtyValues?: boolean
}

FormOptions

Form creation options.

interface FormOptions<T extends FormValuesConstraint<T>> {
  /**
   * Default values, captured as the form's clean baseline when the controller
   * is created. Mutating this object afterwards does not change the baseline.
   */
  defaultValues?: Partial<T>

  /**
   * Externally loaded values, merged over `defaultValues` as the clean
   * baseline. Framework bindings also apply later content changes; use
   * `resetOptions.keepDirtyValues` to preserve edits while pristine fields fill.
   */
  values?: Partial<T>

  /** Controls how framework bindings apply changed `values`. */
  resetOptions?: FormResetOptions

  /**
   * Validation mode.
   */
  mode?: 'onSubmit' | 'onChange' | 'onBlur' | 'all'

  /**
   * Revalidation mode.
   */
  reValidateMode?: 'onChange' | 'onBlur' | 'onSubmit'

  /**
   * Whether to focus the first error field on submit.
   */
  shouldFocusError?: boolean

  /**
   * Form-level validation function.
   */
  validate?: (
    values: T,
  ) => Partial<Record<keyof T, string>> | Promise<Partial<Record<keyof T, string>>>
}

HttpClient

HTTP client interface.

All HTTP providers must implement this interface. An explicit text, blob or arraybuffer parser determines the data type even when a JSON generic is supplied. Keep JSON as the default for mutations returning a record. A successful DELETE with no body already resolves with null data.

Every verb also takes a URL alone, through a signature with the same three parameters on every verb, so a verb chosen at runtime (client[verb](url)) type-checks and a wrapper can implement a verb with an arrow (get: (url, config) => inner.get(url, config)). With a body or a config, choose the verb through request({ method, url, data }) instead: the second argument is the body for post/put/patch but the config for get/delete, so one call cannot serve both.

interface HttpClient {
  /**
   * Base URL for all requests.
   */
  baseURL: string

  /**
   * Default headers for all requests.
   */
  defaultHeaders: Record<string, string>

  /**
   * Makes a generic HTTP request. `data` is a field of THIS config object — the same body
   * `post(url, data, config)` takes as its second argument.
   */
  request<T = unknown>(
    config: FullRequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  request<T = unknown>(
    config: FullRequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  request<T = unknown>(
    config: FullRequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  request<T = unknown>(config: FullRequestConfig): Promise<HttpResponse<T>>

  /**
   * Makes a GET request.
   */
  get<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  get<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  get<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  get<T = unknown>(url: string, config?: undefined, unused?: undefined): Promise<HttpResponse<T>>
  get<T = unknown>(url: string, config?: RequestConfig): Promise<HttpResponse<T>>

  /**
   * Makes a POST request. `data` is the request BODY, not a config object: the wire body is
   * `data` itself, so `post(url, { data: body })` sends `{"data":body}` — pass `body` directly.
   * A config (headers, params) is the THIRD argument.
   */
  post<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  post<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  post<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  post<T = unknown>(url: string, data?: undefined, config?: undefined): Promise<HttpResponse<T>>
  post<T = unknown>(url: string, data?: unknown, config?: RequestConfig): Promise<HttpResponse<T>>

  /**
   * Makes a PUT request. `data` is the request BODY (second argument) — never `{ data: body }`,
   * which sends `{"data":body}`; a config is the THIRD argument.
   */
  put<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  put<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  put<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  put<T = unknown>(url: string, data?: undefined, config?: undefined): Promise<HttpResponse<T>>
  put<T = unknown>(url: string, data?: unknown, config?: RequestConfig): Promise<HttpResponse<T>>

  /**
   * Makes a PATCH request. `data` is the request BODY (second argument) — never `{ data: body }`,
   * which sends `{"data":body}`; a config is the THIRD argument.
   */
  patch<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  patch<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  patch<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  patch<T = unknown>(url: string, data?: undefined, config?: undefined): Promise<HttpResponse<T>>
  patch<T = unknown>(url: string, data?: unknown, config?: RequestConfig): Promise<HttpResponse<T>>

  /**
   * Makes a DELETE request.
   */
  delete<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  delete<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  delete<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  delete<T = unknown>(url: string, config?: undefined, unused?: undefined): Promise<HttpResponse<T>>
  delete<T = unknown>(url: string, config?: RequestConfig): Promise<HttpResponse<T>>

  /**
   * Adds a request interceptor.
   * Returns a function to remove the interceptor.
   */
  addRequestInterceptor(interceptor: RequestInterceptor): () => void

  /**
   * Adds a response interceptor.
   * Returns a function to remove the interceptor.
   */
  addResponseInterceptor(interceptor: ResponseInterceptor): () => void

  /**
   * Adds an error interceptor.
   * Returns a function to remove the interceptor.
   */
  addErrorInterceptor(interceptor: ErrorInterceptor): () => void

  /**
   * Sets the authorization token.
   *
   * A static token: every request carries it until the next `setAuthToken` call. A client
   * that has a `resolver` (registered through
   * `@molecule/app-http`'s `setAuthTokenSource`) ignores this value when it assembles a
   * request — the resolver IS the session, and reading it per request is what keeps a
   * session adopted without an auth event from sending the previous account's bearer. Once
   * the resolver is removed, the static token is sent again.
   */
  setAuthToken(token: string | null): void

  /**
   * Returns the token the client applies to its next request: the resolver's answer when one
   * is registered, else the static token from `setAuthToken`.
   */
  getAuthToken(): string | null

  /** Registers the LIVE token resolver every request of this client reads, or clears it with `null`. */
  setAuthTokenResolver?(resolver: AuthTokenResolver | null): void

  /**
   * Registers a handler for authentication errors (401), with the rejected request's metadata.
   *
   * @param handler - Receives the method, URL and credential state of the rejected request.
   * @returns An unsubscribe function.
   */
  onAuthError(handler: (event: HttpAuthErrorEvent) => void): () => void
}

(The longest member comment is shortened to its first sentence to fit; the full declaration is in node_modules/@molecule/app-http/dist/client.d.ts.)

Router

Client-side router providing navigation, guards, route matching, and history control.

All routing providers must implement this interface.

interface Router {
  /**
   * Returns the current route location (pathname, search, hash, state).
   */
  getLocation(): RouteLocation

  /**
   * Gets the current route params.
   */
  getParams<T extends RouteParams = RouteParams>(): T

  /**
   * Gets the current query params.
   */
  getQuery(): QueryParams

  /**
   * Gets a specific query parameter.
   */
  getQueryParam(key: string): string | undefined

  /**
   * Gets the current hash.
   */
  getHash(): string

  /**
   * Navigates to a path. A path that is only a query or a hash (`'?tab=2'`, `'#top'`) stays on
   * the current page, as React Router's `navigate` does; a hash alone drops the current query.
   */
  navigate(path: string, options?: NavigateOptions): void

  /**
   * Navigates to a named route.
   */
  navigateTo(
    name: string,
    params?: RouteParams,
    query?: QueryParams,
    options?: NavigateOptions,
  ): void

  /**
   * Goes back in history.
   */
  back(): void

  /**
   * Goes forward in history.
   */
  forward(): void

  /**
   * Goes to a specific point in history.
   */
  go(delta: number): void

  /**
   * Updates the current query params.
   */
  setQuery(params: QueryParams, options?: NavigateOptions): void

  /**
   * Updates a specific query parameter.
   */
  setQueryParam(key: string, value: string | undefined, options?: NavigateOptions): void

  /**
   * Updates the current hash.
   */
  setHash(hash: string, options?: NavigateOptions): void

  /**
   * Checks if a path matches the current location.
   *
   * @returns `true` if the path matches the current route.
   */
  isActive(path: string, exact?: boolean): boolean

  /**
   * Matches a path pattern against a pathname.
   */
  matchPath<Params extends RouteParams = RouteParams>(
    pattern: string,
    pathname: string,
  ): RouteMatch<Params> | null

  /**
   * Generates a URL from a named route.
   */
  generatePath(name: string, params?: RouteParams, query?: QueryParams): string

  /**
   * The `href` an anchor to the in-app `path` carries, as the native router's own link
   * writes it (its base path prefixed, or `#/…` under a hash history), so a middle-click,
   * a new tab or a copied link opens the same page a click does. A `path` that is only a
   * query or a hash (`'?tab=2'`, `'#top'`) is the current page's, as `navigate` reads it
   * and as React Router's `<Link>` writes it: `'#top'` on `/docs?x=1` is `/docs#top`.
   *
   * @param path - Pathname with optional query string and hash, as passed to `navigate`.
   * @returns The `href`.
   */
  createHref(path: string): string

  /**
   * Calls `listener` once after each navigation the router commits, however it started (a
   * link, the back button, `navigate`), with the new location and the navigation action.
   * A router calls it before the browser paints the new page, so a component that renders
   * from a listener (the framework bindings' `useLocation` and `useParams` do) shows the new
   * location in the same paint as the new page. Molecule's router conformance tests check
   * that at every paint.
   *
   * @param listener - Called with the new location and the navigation action.
   * @returns Stops calling `listener`.
   */
  subscribe(listener: RouteChangeListener): () => void

  /**
   * Adds a navigation guard.
   */
  addGuard(guard: NavigationGuard): () => void

  /**
   * Registers route definitions.
   */
  registerRoutes(routes: RouteDefinition[]): void

  /**
   * Gets all registered routes.
   */
  getRoutes(): RouteDefinition[]

  /**
   * Destroys the router.
   */
  destroy(): void
}

RouterConfig (deprecated)

Deprecated: Use BrowserRouterConfig (createBrowserRouter) or MemoryRouterConfig (createMemoryRouter): each takes only the options it acts on.

Configuration options for creating a router instance.

interface RouterConfig {
  /**
   * Router mode.
   */
  mode?: 'history' | 'hash' | 'memory'

  /**
   * Base path.
   */
  basePath?: string

  /**
   * Initial routes.
   */
  routes?: RouteDefinition[]
}

StoreConfig

Configuration for creating a store (initial state, optional name, and middleware chain).

interface StoreConfig<T> {
  /**
   * Initial state value.
   */
  initialState: T

  /**
   * Optional name for debugging.
   */
  name?: string

  /**
   * Optional middleware functions.
   */
  middleware?: StoreMiddleware<T>[]
}

Store

Reactive state container with getState, setState, subscribe, and destroy.

All state management providers must implement this interface.

interface Store<T> {
  /**
   * Gets the current state.
   */
  getState(): T

  /**
   * Sets the state (partial or via updater function).
   */
  setState(partial: Partial<T> | ((state: T) => Partial<T>)): void

  /**
   * Subscribes to state changes.
   * Returns an unsubscribe function.
   */
  subscribe(listener: StateListener<T>): () => void

  /**
   * Destroys the store and cleans up subscriptions.
   */
  destroy(): void
}

Theme

Complete theme definition.

interface Theme {
  name: string
  mode: 'light' | 'dark'
  colors: ThemeColors
  breakpoints: ThemeBreakpoints
  spacing: ThemeSpacing
  typography: ThemeTypography
  borderRadius: ThemeBorderRadius
  shadows: ThemeShadows
  transitions: ThemeTransitions
  zIndex: ThemeZIndex
}

SafeAreaInsets

Safe area inset values in points.

interface SafeAreaInsets {
  top: number
  right: number
  bottom: number
  left: number
}

UseBackHandlerOptions

Options for the useBackHandler hook.

interface UseBackHandlerOptions {
  /** Whether the handler is enabled. Defaults to true. */
  enabled?: boolean
}

UseAppStateResult

Result from the useAppState hook.

interface UseAppStateResult {
  /** Current app state: 'active' | 'background' | 'inactive' */
  appState: string
  /** Whether the app is in the foreground */
  isActive: boolean
}

UseKeyboardHeightResult

Result from the useKeyboardHeight hook.

interface UseKeyboardHeightResult {
  /** Current keyboard height in points (0 when hidden) */
  keyboardHeight: number
  /** Whether the keyboard is currently visible */
  isKeyboardVisible: boolean
}

UseChangePasswordReturn

Return type for useChangePassword hook.

interface UseChangePasswordReturn {
  status: UsePromiseState<void>['status']
  error: UsePromiseState<void>['error']
  changePassword: (oldPassword: string, newPassword: string) => Promise<void>
  reset: () => void
}

UseDeviceResult

Hook return type.

interface UseDeviceResult {
  deviceInfo: DeviceInfo
  screenInfo: ScreenInfo
  hardwareInfo: HardwareInfo
  featureSupport: FeatureSupport
  supports: (feature: keyof FeatureSupport) => boolean
  isOnline: () => boolean
  isStandalone: () => boolean
  language: string
  languages: string[]
}

UseFormOptions

Options for useForm hook.

Every FormOptions field is supported. createForm is only an override — omit it and the hook creates the controller through the bonded forms provider (createForm from @molecule/app-forms), which uses the built-in native provider until the app bonds its own.

interface UseFormOptions<T extends FormValuesConstraint<T>> extends FormOptions<T> {
  /** External values preserve dirty fields by default. Set keepDirtyValues: false to replace them explicitly. */
  resetOptions?: FormResetOptions
  /** New record identity. Serialize composite keys; fresh objects/arrays must not reset drafts on each render. */
  resetKey?: string | number | boolean | bigint | null
  /**
   * Explicit form factory for this one form. Defaults to the bonded forms
   * provider; pass it only to pin a specific provider instance.
   */
  createForm?: (options: FormOptions<T>) => FormController<T>
}

UseFormResult

Result of useForm hook.

interface UseFormResult<T extends FormValuesConstraint<T>> {
  // State
  formState: FormState<T>
  isValid: boolean
  isDirty: boolean
  isSubmitting: boolean

  // Field methods
  register: (
    name: keyof T,
    options?: Omit<RegisterOptions, 'name'> & { name?: string },
  ) => FieldRegistration
  getValue: <K extends keyof T>(name: K) => T[K]
  setValue: <K extends keyof T>(name: K, value: T[K]) => void
  getError: (name: keyof T) => string | undefined
  setError: (name: keyof T, error: string | undefined) => void
  clearErrors: () => void

  // Form methods
  handleSubmit: (
    onSubmit: (values: T) => void | Promise<void>,
  ) => (event?: React.FormEvent) => Promise<void>
  reset: (values?: Partial<T>) => void
  updateValues: (values: Partial<T>, resetOptions?: FormUpdateOptions) => void
  /** Whole-form state tuple: edits mark only changed fields dirty; fills preserve them. */
  asState(): readonly [
    T,
    Dispatch<SetStateAction<T>>,
    (values: Partial<T> | ((previous: T) => Partial<T>)) => void,
  ]
  /** One field as [value, edit, fill]. Fill preserves edits made before data arrives. */
  asState<K extends keyof T>(
    name: K,
  ): readonly [T[K], Dispatch<SetStateAction<T[K]>>, Dispatch<SetStateAction<T[K]>>]
  validate: () => Promise<boolean>
}

UseHttpState

State for async HTTP operations.

interface UseHttpState<T> {
  data: T | null
  loading: boolean
  error: Error | null
}

UseHttpResult

Result of useHttp hook.

interface UseHttpResult<T> extends UseHttpState<T> {
  /**
   * Runs the request and resolves with its own data, or `null` on failure,
   * even when a newer request or `reset` has superseded its displayed state.
   *
   * This function is IDENTITY-STABLE for as long as `method`, `url` and the HTTP
   * client do not change, so it is safe in a `useEffect` dependency array. Its
   * request options are read when it is CALLED, from the latest committed render.
   */
  execute: () => Promise<T | null>
  reset: () => void
}

UseHttpOptions

Options for useHttp hook.

Every request option — headers, params, body data, signal, onSuccess, onError — is read at the moment execute runs, not when the hook rendered, so an inline object or callback needs no memoizing. Only immediate is read on mount.

interface UseHttpOptions<T> extends RequestConfig {
  /**
   * Whether to execute the request immediately on mount.
   */
  immediate?: boolean
  /**
   * Callback for each request that succeeds while mounted, including a request
   * superseded by another `execute` or `reset`. Read `data` from the hook when
   * only the newest request's result should drive the UI.
   */
  onSuccess?: (data: T) => void
  /**
   * Callback for each request that fails while mounted, including a request
   * superseded by another `execute` or `reset`.
   */
  onError?: (error: Error) => void
}

UseLoginReturn

Return type for useLogin hook.

interface UseLoginReturn<T = unknown> {
  status: UsePromiseState<AuthResult<T>>['status']
  value: UsePromiseState<AuthResult<T>>['value']
  error: UsePromiseState<AuthResult<T>>['error']
  login: (credentials: LoginCredentials) => Promise<AuthResult<T>>
  reset: () => void
}

UseOAuthReturn

Return type for useOAuth hook.

interface UseOAuthReturn {
  providers: string[]
  getOAuthUrl: (provider: string) => string
  /** Full-page redirect to the provider (default). The opener page navigates away. */
  redirect: (provider: string) => void
  /**
   * Open the provider in a popup so the opener page does NOT navigate. On success
   * the session is established in the opener in place and `config.onSuccess` fires;
   * on failure `config.onError` fires. Falls back to a full-page `redirect`
   * when the popup is blocked.
   */
  loginViaPopup: (provider: string) => void
}

UseOAuthConfig

OAuth configuration for useOAuth: the app's oauthConfig (from its config.ts), the same type under the same name in every framework binding.

interface UseOAuthConfig {
  /** Base URL for the API server (e.g. "https://api.example.com"). */
  baseURL?: string
  /** List of supported OAuth provider names (e.g. ["google", "github"]). */
  oauthProviders?: string[]
  /** Path prefix for OAuth routes (defaults to "/oauth"). */
  oauthEndpoint?: string
  /** Path for the OAuth login POST endpoint (defaults to "/users/log-in/oauth"). */
  loginEndpoint?: string
  /** Callback after successful OAuth login. */
  onSuccess?: () => void
  /** Callback on OAuth login failure. */
  onError?: (error: string) => void
  /**
   * How the page leaves for the provider: `UseOAuthReturn.redirect` and the
   * blocked-popup fallback call it with the provider URL. Defaults to a full-page
   * navigation (`window.location.href = url`); pass an in-app browser opener on
   * native, or a router's external navigation.
   */
  navigate?: (url: string) => void
}

UseOptimisticToggleOptions

Options for useOptimisticToggle.

interface UseOptimisticToggleOptions {
  /** The loaded server value. Mount the control only after its record exists. */
  value: boolean
  /** Saves the DESIRED value and returns the server-confirmed value; reject on failure. */
  commit: (desired: boolean) => Promise<boolean>
  /** Receives the newest failed save and the confirmed value restored by the controller. */
  onError?: (error: unknown, value: boolean) => void
}

UseOptimisticToggleResult

A boolean to render and an argument-free action, suitable for any button or switch.

interface UseOptimisticToggleResult extends OptimisticValueState<boolean> {
  /** Flips the latest displayed value, including clicks made before React renders again. */
  toggle: () => void
}

UseOptimisticValueResult

What useOptimisticValue returns: the state to render and the two ways to change it.

interface UseOptimisticValueResult<T> extends OptimisticValueState<T> {
  /**
   * Shows `next` at once and saves it, after any save already running.
   *
   * @param next - The value the person chose.
   */
  set: (next: T) => void

  /**
   * Like `set`, computed from the value shown now (`update((on) => !on)`).
   *
   * @param change - Computes the next value from the value shown now.
   */
  update: (change: (current: T) => T) => void
}

UsePasswordResetReturn

Return type for usePasswordReset hook.

interface UsePasswordResetReturn {
  requestStatus: UsePromiseState<void>['status']
  requestError: UsePromiseState<void>['error']
  confirmStatus: UsePromiseState<void>['status']
  confirmError: UsePromiseState<void>['error']
  requestReset: (data: PasswordResetRequest) => Promise<void>
  confirmReset: (data: PasswordResetConfirm) => Promise<void>
  reset: () => void
}

UsePlatformResult

Hook return type.

interface UsePlatformResult {
  platform: Platform
  isNative: boolean
  isMobile: boolean
  isDesktop: boolean
  isWeb: boolean
  isDevelopment: boolean
  isProduction: boolean
  isPlatform: (...platforms: Platform[]) => boolean
}

UseProfileFormOptions

Configuration for a profile form; transport stays in the auth bond.

TValues is the page's own controlled-values type, named once as an interface or a type alias — both satisfy the shared form-values constraint.

interface UseProfileFormOptions<TUser, TValues extends FormValuesConstraint<TValues>> extends Omit<
  UseFormOptions<TValues>,
  'defaultValues'
> {
  /** Complete controlled-field defaults, including blank write-only fields. */
  defaultValues: TValues
  /**
   * Optional additional account identity check; changing it discards prior edits.
   * By default ownership follows the auth client's session revision, so editable
   * fields can change during a save. Providers without getSessionRevision must
   * supply this callback with an identity that remains stable across profile edits.
   */
  getIdentity?: (user: TUser) => string
  /** Maps the current/saved user into controlled values, e.g. nullable text to ''. */
  toValues: (user: TUser) => TValues
  /**
   * Maps ONLY changed fields into an API patch. Omit blank optional credentials
   * here; preserve undefined/absent fields rather than turning them into null.
   * The second argument is the complete value snapshot taken at submit time.
   */
  toPatch: (changes: Partial<TValues>, values: Readonly<TValues>) => Partial<TUser>
  /**
   * Propagates the server's saved user to other caches, then navigates if needed.
   * Awaited before submission finishes. The auth client already persists and
   * publishes the saved user; never seed caches from the submitted patch.
   */
  onSaved?: (user: TUser) => void | Promise<void>
}

UseProfileFormResult

Controlled profile form state and native form bindings.

interface UseProfileFormResult<TUser, TValues extends FormValuesConstraint<TValues>> extends Omit<
  UseFormResult<TValues>,
  'register' | 'handleSubmit' | 'reset'
> {
  /** The shared auth user's current profile. */
  user: TUser | null
  /** A user has been loaded; disable submission until this is true. */
  ready: boolean
  /**
   * The latest save/propagation failure. Rejected saves retain edits; a failed
   * onSaved callback can be retried by submit without repeating the mutation.
   */
  error: unknown
  /** Native input/textarea bindings with the field's concrete value type. */
  register: <K extends keyof TValues>(
    name: K,
    options?: Parameters<UseFormResult<TValues>['register']>[1],
  ) => Omit<FieldRegistration, 'value'> & { value: TValues[K] }
  /** Bind to the native form, with a type="submit" button inside it. */
  formProps: { onSubmit: (event: Pick<KitEvent, 'preventDefault'>) => void }
  /**
   * Validates and saves one submit-time snapshot. Concurrent submits share the
   * same promise. Resolves undefined on validation, save or propagation failure.
   */
  submit: () => Promise<TUser | undefined>
  /** Discards edits and restores the newest loaded/saved profile baseline. */
  reset: () => void
}

UsePromiseState

Extended promise state with actions.

interface UsePromiseState<T> {
  status: PromiseStatus
  value: T | null
  error: Error | null
  cancel: (message?: string) => void
  reset: () => void
}

UseSignupReturn

Return type for useSignup hook.

interface UseSignupReturn<
  T = unknown,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
> {
  status: UsePromiseState<AuthResult<T>>['status']
  value: UsePromiseState<AuthResult<T>>['value']
  error: UsePromiseState<AuthResult<T>>['error']
  signup: (data: RegisterData<TRegister>) => Promise<AuthResult<T>>
  reset: () => void
}

UseStorageValueOptions

Options for useStorageValue hook.

interface UseStorageValueOptions<T> {
  /**
   * Default value if key doesn't exist.
   */
  defaultValue?: T
  /**
   * Whether to sync across tabs/windows (if supported by storage provider).
   */
  sync?: boolean
}

UseStorageValueResult

Result of useStorageValue hook.

interface UseStorageValueResult<T> {
  value: T | undefined
  setValue: (value: T) => Promise<void>
  removeValue: () => Promise<void>
  loading: boolean
  error: Error | null
}

UseStoragePreferenceOptions

Options for useStoragePreference.

interface UseStoragePreferenceOptions<T> {
  /**
   * Value reported until the provider supplies one. It is NEVER written to
   * storage: a default is a display fallback, not a decision the user made.
   */
  defaultValue?: T
}

UseStoragePreferenceResult

Result of useStoragePreference.

interface UseStoragePreferenceResult<T> {
  /** The persisted value, or `defaultValue` while none is known. */
  value: T | undefined
  /**
   * Writes the value through the preference store: subscribers update
   * immediately and persistence is best-effort.
   */
  setValue: (next: T | ((previous: T | undefined) => T)) => void
  /** Removes the key through the preference store. */
  removeValue: () => void
  /**
   * `true` once the store has a definite answer — the synchronous snapshot on
   * a synchronous provider, or the hydration result on an asynchronous one.
   */
  ready: boolean
}

UseVerifyPaymentReturnOptions

Options for useVerifyPaymentReturn.

interface UseVerifyPaymentReturnOptions {
  /**
   * Provider name to verify with, when the return URL carries no `provider`
   * query parameter. Leave unset to verify only what the URL names.
   */
  provider?: string

  /** Set `false` to skip verification entirely (e.g. behind a feature flag). */
  enabled?: boolean

  /**
   * Remove the provider's query parameters from the address bar once the
   * purchase is verified, so a reload (or a shared link) cannot replay the
   * verification. Defaults to `true`.
   */
  cleanUrl?: boolean

  /** Called once, after the purchase verifies. */
  onVerified?: () => void

  /** Called when verification fails. */
  onError?: (error: Error) => void
}

UseVerifyPaymentReturnResult

State of the post-checkout verification.

interface UseVerifyPaymentReturnResult {
  /**
   * `idle` when this page load is not a checkout return (no transaction id in
   * the URL) or auth is still hydrating; `verifying` while the API call is in
   * flight; then `verified` or `failed`.
   */
  status: VerifyPaymentReturnStatus

  /** `true` when the URL identifies a purchase to verify. */
  isReturn: boolean

  /** The provider named by the URL (or the `provider` option). */
  provider: string | null

  /** The provider transaction/session id read from the URL. */
  transactionId: string | null

  /** Why verification failed, when it did. */
  error: Error | null

  /** Re-run the verification — wire this to a retry button. */
  retry: () => void
}

UseVersionResult

Hook return type.

interface UseVersionResult {
  state: VersionState
  isUpdateAvailable: boolean
  isChecking: boolean
  isServiceWorkerWaiting: boolean
  newVersion: string | undefined
  checkForUpdates: () => Promise<boolean>
  applyUpdate: (options?: { force?: boolean }) => void
  dismissUpdate: () => void
  startPeriodicChecks: (options?: UpdateCheckOptions) => void
  stopPeriodicChecks: () => void
}

ProviderProps

Props for provider components.

interface ProviderProps {
  children: ReactNode
}

SessionReadyProps

Props for the SessionReady component.

interface SessionReadyProps {
  /** What renders once the initial restore settles — signed in, signed out, or unavailable. */
  children: ReactNode
  /** What renders while the session restore is still undecided; default nothing. */
  fallback?: ReactNode
}

StateProviderProps

Props for state provider component.

interface StateProviderProps extends ProviderProps {
  provider: StateProvider
}

AuthProviderProps

Props for auth provider component.

interface AuthProviderProps<T = unknown> extends ProviderProps {
  client: AuthClient<T>
  /** Wait for initial session restoration by default. Set false for a deliberately ungated shell or synchronous SSR. */
  awaitSession?: boolean
  /** Content shown while the initial session status is loading; default nothing. */
  sessionFallback?: ReactNode
}

ThemeProviderProps

Props for theme provider component.

interface ThemeProviderProps extends ProviderProps {
  provider: ThemeProvider
  /**
   * Not read: the theme a page starts on comes from the theme provider itself (`defaultTheme` and the
   * saved choice in `@molecule/app-theme-css-variables`), and setting one here would overwrite a
   * visitor's saved theme on every load.
   *
   * @deprecated Ignored. Pass `defaultTheme` to the theme provider (`createCSSVariablesThemeProvider({ defaultTheme })`) instead.
   */
  initialTheme?: string
}

RouterProviderProps

Props for router provider component.

interface RouterProviderProps extends ProviderProps {
  router: Router
  /**
   * The component that renders the matched child route where a layout or guard puts it (React
   * Router's `Outlet`), so `<RoutedView />` works under any routing bond. A routing bond passes
   * it; leave it out when the bond has no such component (Next.js gives a layout its page as
   * children), and `<RoutedView />` then throws an error saying so.
   */
  routedView?: ComponentType
  /**
   * A hook that returns the route params of the component calling it, from a routing bond whose
   * native router scopes params to the component (React Router's `useParams`, which is empty
   * above the matched route). `useRouter().params` and `useParams()` call it and fall back to
   * `router.getParams()` when it returns none. Read once, at the provider's first render: pass a
   * module-level function. Leave it out when the router answers params anywhere.
   */
  useRouteParams?: () => RouteParams
}

I18nProviderProps

Props for i18n provider component.

interface I18nProviderProps extends ProviderProps {
  provider: I18nProvider
}

HttpProviderProps

Props for http provider component.

interface HttpProviderProps extends ProviderProps {
  client: HttpClient
}

StorageProviderProps

Props for storage provider component.

interface StorageProviderProps extends ProviderProps {
  provider: StorageProvider
}

LoggerProviderProps

Props for logger provider component.

interface LoggerProviderProps extends ProviderProps {
  provider: LoggerProvider
}

WorkspaceProviderProps

Props for workspace provider component.

interface WorkspaceProviderProps extends ProviderProps {
  provider: WorkspaceProvider
}

EditorProviderProps

Props for editor provider component.

interface EditorProviderProps extends ProviderProps {
  provider: EditorProvider
}

PreviewProviderProps

Props for preview provider component.

interface PreviewProviderProps extends ProviderProps {
  provider: PreviewProvider
}

MoleculeProviderProps

Properties for molecule provider.

interface MoleculeProviderProps extends ProviderProps {
  state?: StateProvider
  auth?: AuthClient<unknown>
  /**
   * Render the app only once `auth` leaves its initial loading status (`SessionReadyProps`). Defaults to true.
   * With the bundled JWT client, a stored token AND cached user restore synchronously.
   * Token-only and cookie-only sessions need an asynchronous current-user request;
   * until it answers `useAuth().user` is `null` — a public page's signed-in action
   * (`if (!user) return`, a redirect to `/login`) then treats a signed-in visitor as signed out.
   * When restoration succeeds, every page's first render reads the restored user. An
   * `'unavailable'` session also renders, but remains unconfirmed and may have a null user.
   * A visitor with no session candidate settles synchronously without a request.
   * Ignored without `auth`. Synchronous SSR renders the fallback for a loading client:
   * initialize a request-scoped client first, or set this false for an ungated SSR shell.
   */
  awaitSession?: boolean
  /** Rendered instead of the app while `MoleculeProviderProps.awaitSession` waits; default nothing. */
  sessionFallback?: ReactNode
  theme?: ThemeProvider
  router?: Router
  i18n?: I18nProvider
  http?: HttpClient
  storage?: StorageProvider
  logger?: LoggerProvider
  workspace?: WorkspaceProvider
  editor?: EditorProvider
  preview?: PreviewProvider
}

UseStoreOptions

Hook options for useStore.

interface UseStoreOptions<T, S> {
  selector?: (state: T) => S
  equalityFn?: (a: S, b: S) => boolean
}

SelectingStoreOptions

Hook options that pick part of the store: a selector is required, so the selected type S always comes from it.

interface SelectingStoreOptions<T, S> extends UseStoreOptions<T, S> {
  /** Picks the value the hook returns from the store's state. */
  selector: (state: T) => S
}

UseAuthOptions

Hook options for useAuth.

interface UseAuthOptions {
  /**
   * Whether to automatically refresh the token on mount.
   */
  autoRefresh?: boolean
}

UseAuthResult

Hook result for useAuth.

interface UseAuthResult<
  T = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
> {
  /**
   * The session state as one value — render from this instead of combining
   * `initialized`/`authenticated`/`loading`. A stored token AND user make it
   * `'authenticated'` on the first render; only `'loading'` means "no decision
   * yet", so a route guard waits on that and nothing else. `'unavailable'` keeps
   * a session candidate for retry and can have a null profile; redirect only on
   * `'unauthenticated'`.
   */
  status: AuthState<T>['status']
  state: AuthState<T>
  login: AuthClient<T>['login']
  logout: AuthClient<T>['logout']
  register: AuthClient<T, TRegister>['register']
  refresh: AuthClient<T>['refresh']
  /** Save through the configured auth transport and persist/publish its canonical profile. */
  updateProfile: AuthClient<T>['updateProfile']
  setUser: AuthClient<T>['setUser']
  /**
   * Adopt a session an exchange outside the client already established (an
   * OAuth code→token redirect, the app's own sign-in endpoint) in ONE update:
   * the token and user are stored and the hook's consumers see the client as
   * `authenticated` immediately.
   *
   * `setUser` alone does NOT sign the client in, and `setAccessToken` changes
   * storage only — using those two for a caller-issued session leaves every
   * `authenticated` read signed out.
   */
  setSession: AuthClient<T>['setSession']
  /** Whether a session is authenticated locally; this can be false while unavailable. */
  isAuthenticated: boolean
  isLoading: boolean
  /** The cached profile, which can be null while an unavailable candidate is retained. */
  user: T | null
}

UseThemeResult

Hook result for useTheme.

interface UseThemeResult {
  theme: Theme
  themeName: string
  setTheme: (name: string) => void
  toggleTheme: () => void
  mode: 'light' | 'dark'
}

UseRouterResult

Hook result for useRouter.

interface UseRouterResult {
  location: Router['getLocation'] extends () => infer R ? R : never
  params: Record<string, string>
  query: QueryParams
  navigate: Router['navigate']
  navigateTo: Router['navigateTo']
  back: Router['back']
  forward: Router['forward']
  isActive: Router['isActive']
}

UseTranslationResult

Hook result for useTranslation.

interface UseTranslationResult {
  /**
   * Translates a key in the active locale. A new function after each locale
   * change, so a value memoized on `[t]` refreshes; `useT()` returns one that
   * keeps its identity across locale changes.
   */
  t: I18nProvider['t']
  /** The active locale code. */
  locale: string
  /** Switches the active locale. Same function while the provider is unchanged. */
  setLocale: I18nProvider['setLocale']
  /** The registered locales; a new list only after a locale notification. */
  locales: ReturnType<I18nProvider['getLocales']>
  /** Formats a number for the active locale. Same function while the provider is unchanged. */
  formatNumber: I18nProvider['formatNumber']
  /** Formats a date for the active locale. Same function while the provider is unchanged. */
  formatDate: I18nProvider['formatDate']
  /** The active locale's text direction. */
  direction: 'ltr' | 'rtl'
}

UseWorkspaceResult

Hook result for useWorkspace.

interface UseWorkspaceResult {
  layout: WorkspaceLayout
  activePanel: PanelId | null
  collapsedPanels: Set<PanelId>
  togglePanel: (panelId: PanelId) => void
  resizePanel: (panelId: PanelId, size: number) => void
  setActivePanel: (panelId: PanelId) => void
  resetLayout: () => void
}

UseEditorResult

Hook result for useEditor.

interface UseEditorResult {
  tabs: EditorTab[]
  activeFile: string | null
  openFile: (file: EditorFile) => void
  closeFile: (path: string) => void
  getContent: () => string | null
  setContent: (path: string, content: string) => void
  setActiveTab: (path: string) => void
  mount: EditorProvider['mount']
  dispose: () => void
  focus: () => void
  openDiff: (file: DiffFile) => void
  closeDiff: () => void
  pinTab: (path: string) => void
  addExtraLib: (content: string, filePath: string) => void
  onFixWithAI: (callback: (request: FixWithAIRequest) => void) => () => void
}

UsePreviewResult

Hook result for usePreview.

interface UsePreviewResult {
  state: PreviewState
  setUrl: (url: string) => void
  refresh: () => void
  setDevice: (device: DeviceFrame) => void
  openExternal: () => void
  /**
   * Records a navigation the running preview reported via its `molecule:navigate`
   * message — updates the displayed current location without reloading the iframe.
   * Pass `isReplace` when the preview REPLACED its current history entry (a
   * `replaceState` redirect/canonicalization) so the forward stack is preserved
   * instead of truncated (a `pushState`, the default, truncates forward).
   */
  recordNavigation: (url: string, isReplace?: boolean) => void
  /** Navigates the preview to the previous navigation-history entry (Back). */
  back: () => void
  /** Navigates the preview to the next navigation-history entry (Forward). */
  forward: () => void
}

Types

AsyncSetState

Async-capable setState function.

type AsyncSetState<T> = (value: T | ((prev: T) => T) | Promise<T | ((prev: T) => T)>) => void
  • value — The new state value, an updater function receiving previous state, or a Promise resolving to either.

AsyncExtendState

Async-capable extendState function for partial updates.

type AsyncExtendState<T> = (
  partial: Partial<T> | ((prev: T) => Partial<T>) | Promise<Partial<T> | ((prev: T) => Partial<T>)>,
) => void

UseCapacitorAppResult

Hook return type.

type UseCapacitorAppResult = CapacitorAppState & {
  initialize: () => Promise<void>
}

VerifyPaymentReturnStatus

How far the return-page verification has got.

type VerifyPaymentReturnStatus = 'idle' | 'verifying' | 'verified' | 'failed'

UseTShorthandOptions

Options for the shorthand form of UseTFunction: the fallback text is passed positionally, so only count remains here.

type UseTShorthandOptions = Omit<TranslateOptions, 'defaultValue'>

UseTFunction

Translation function returned by useT().

Two compatible call forms:

  • t(key, values?, options?) — the I18nProvider.t signature.
  • t(key, fallback, options?) — a string second argument is the inline English defaultValue, with optional count for pluralization.

Its identity is stable while the i18n provider instance is unchanged, so it can be used directly as an effect dependency.

type UseTFunction = TranslateFunctionWithFallback

Functions

useAppState()

Tracks whether the app is in the foreground, background, or inactive.

Reads React Native's AppState as an external store, so the first render already reports the real state and a change between that render and the subscription is not missed. Falls back to 'active' on platforms where AppState is unavailable.

function useAppState(): UseAppStateResult

Returns: Current app state and whether the app is active.

useBackHandler(handler, options)

Registers a handler for the Android hardware back button.

Return true from the handler to prevent the default back behavior, or false to allow it.

function useBackHandler(handler: () => boolean, options?: UseBackHandlerOptions): void
  • handler — Callback invoked when the hardware back button is pressed.
  • options — Optional configuration.

useKeyboardHeight()

Tracks soft keyboard visibility and height.

Uses React Native's Keyboard API. Falls back to hidden state on platforms where Keyboard is unavailable.

function useKeyboardHeight(): UseKeyboardHeightResult

Returns: Current keyboard height and visibility state.

useSafeArea()

Returns the current safe area insets from react-native-safe-area-context.

Must be used within a SafeAreaProvider. Falls back to zero insets if the context is unavailable.

The peer's hook is called unconditionally on every render once the module is installed, so its call order is stable; when it is not installed the hook consistently returns zeros for every input.

function useSafeArea(): SafeAreaInsets

Returns: Safe area insets for the current device.

useAsyncState(initialState)

Hook like useState but accepts Promises and supports partial state extension.

function useAsyncState<T>(initialState: T): [T, AsyncSetState<T>, AsyncExtendState<T>]
  • initialState — Initial state value

Returns: Tuple of [state, asyncSetState, asyncExtendState]

useAuthClient()

Hook to access the auth client from context.

Pass the same generics the client was created with — useAuthClient<MyUser, { username: string }>() — so register() accepts the app's own fields.

function useAuthClient<
  T = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(): AuthClient<T, TRegister>

Returns: The auth client from context

useAuth(options)

Hook for authentication state and actions.

status === 'loading' is undecided: wait for it and redirect only on status === 'unauthenticated'. 'unavailable' keeps the session candidate for retry, but isAuthenticated can be false and user can be null while a token/cookie-only restore has no cached profile. A restore failure other than 401/403 never signs out.

Pass the app's user type — the SAME type used for the auth client and its config (createJWTAuthClient<MyUser>, AuthClientConfig<MyUser>) — so user and setSession/setUser are typed for the pages: useAuth<MyUser>(). Save profile edits with updateProfile(patch): it uses the configured auth transport and publishes the saved user to every subscriber before resolving. An app-owned mutation instead passes its canonical response to setUser. setUser(null) ends the session; it does not reload or refresh a saved profile. Do not clear the user after a successful save. Use logout() for the separate, intentional sign-out action.

For a sign-in the app runs itself (an OAuth redirect, a custom endpoint that already issued the token), call setSession({ accessToken, user }): it adopts the token and profile atomically and every consumer of this hook sees status: 'authenticated' at once. setUser alone does not sign in.

To create an account, use const { register } = useAuth<MyUser>() and await register({ email, password, name }). Registration returns the auth client's AuthResult<MyUser>; there is no separate useRegister hook.

An app whose API takes its OWN registration fields passes the client's second generic here too — useAuth<MyUser, { username: string }>() — so register({ email, password, username }) is typed exactly like the client call (and mapRequestBody receives that payload as its first argument). Without it, register accepts only the base fields.

function useAuth<
  T = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(options?: UseAuthOptions): UseAuthResult<T, TRegister>
  • options — Hook options

Returns: Auth state and action methods

useUser()

Hook to get just the authenticated user.

function useUser<T = UserProfile>(): T | null

Returns: The authenticated user or null

useIsAuthenticated()

Hook to check if user is authenticated.

function useIsAuthenticated(): boolean

Returns: Whether the user is authenticated

useCapacitorApp(options)

Hook for Capacitor app initialization and state management.

Creates a CapacitorApp coordinator on mount, subscribes to state changes, and auto-initializes. Cleans up listeners on unmount via destroy().

function useCapacitorApp(options?: CapacitorAppOptions): UseCapacitorAppResult
  • options — Capacitor app configuration options

Returns: Current app state and an initialize function for manual re-initialization

useChangePassword()

Hook for changing password with async state tracking.

function useChangePassword(): UseChangePasswordReturn

Returns: Change password state and action

useDevice()

Hook for device information.

Uses module-level getProvider() — device info is a singleton, not context-provided. Device info is static and doesn't change at runtime, so this uses useMemo.

function useDevice(): UseDeviceResult

Returns: Device information and utility methods

useEditorProvider()

Access the editor provider from context.

function useEditorProvider(): EditorProvider

Returns: The EditorProvider instance from the nearest EditorContext.

useEditor()

Hook for code editor management.

tabs and activeFile always come from the provider's own tab list: activeFile is the path of the tab marked isActive, or null when no tab is. They are read at mount (tabs opened before the component mounted show at once), on every provider change event, and after each action that changes the tab list (openFile, closeFile, setActiveTab, openDiff, closeDiff, pinTab).

function useEditor(): UseEditorResult

Returns: Editor state and controls: tabs, activeFile, openFile, closeFile, getContent, setContent, setActiveTab, mount, dispose, and focus.

useForm(options)

Hook for form state management.

Needs no setup: until the app bonds a forms provider, the built-in native one is used. Creates its controller through the bonded forms provider, so a React app wires a form library once (setProvider from @molecule/app-forms) and every form picks it up. Passing createForm overrides that for one form.

function useForm<T extends FormValuesConstraint<T> = Record<string, unknown>>(
  options?: UseFormOptions<T>,
): UseFormResult<T>
  • options — Form options. defaultValues, mode and the form-level validate are forwarded to the provider. When values changes by content, it becomes the new baseline; resetOptions.keepDirtyValues retains edited fields while pristine fields take the loaded values. Omit the options entirely for a form whose fields are registered with their own defaults.

Returns: Form state and methods

useWatch(form, name)

Hook to watch a specific field value.

function useWatch<T extends FormValuesConstraint<T>, K extends keyof T>(
  form: FormController<T>,
  name: K,
): T[K]
  • form — Form controller
  • name — Field name to watch

Returns: Current field value

useFieldState(form, name)

Hook to get field-level state.

function useFieldState<T extends FormValuesConstraint<T>>(
  form: FormController<T>,
  name: keyof T,
): FieldState<T[keyof T]>
  • form — Form controller
  • name — Field name

Returns: Field state (value, error, touched, dirty, valid)

useHttpClient()

Hook to access the HTTP client from context.

function useHttpClient(): HttpClient

Returns: The HTTP client from context

useHttp(method, url, options)

Hook for making HTTP requests with state management.

execute keeps one identity while method, url and the HTTP client stay the same — across the hook's own loading/data updates, parent rerenders, and inline options or callbacks — so useEffect(() => { void execute() }, [execute]) runs once per request target instead of looping. The current headers, body, signal and callbacks are read when execute is called, so a later manual call always sends what the latest committed render passed. Changing method, url or the client does replace execute (it selects a different request) and re-runs such an effect.

function useHttp<T>(
  method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
  url: string,
  options?: UseHttpOptions<T>,
): UseHttpResult<T>
  • method — HTTP method
  • url — Request URL
  • options — Request options, read at call time

Returns: Request state and execute function

useGet(url, options)

Hook for GET requests.

function useGet<T>(url: string, options?: UseHttpOptions<T>): UseHttpResult<T>
  • url — Request URL to fetch from.
  • options — HTTP request options including callbacks and request config.

Returns: Request state (data, loading, error) and controls (execute, reset).

usePost(url, options)

Hook for POST requests.

function usePost<T>(url: string, options?: UseHttpOptions<T>): UseHttpResult<T>
  • url — Request URL to post to.
  • options — HTTP request options including body data and callbacks.

Returns: Request state (data, loading, error) and controls (execute, reset).

usePut(url, options)

Hook for PUT requests.

function usePut<T>(url: string, options?: UseHttpOptions<T>): UseHttpResult<T>
  • url — Request URL to send the PUT request to.
  • options — HTTP request options including body data and callbacks.

Returns: Request state (data, loading, error) and controls (execute, reset).

usePatch(url, options)

Hook for PATCH requests.

function usePatch<T>(url: string, options?: UseHttpOptions<T>): UseHttpResult<T>
  • url — Request URL to send the PATCH request to.
  • options — HTTP request options including partial body data and callbacks.

Returns: Request state (data, loading, error) and controls (execute, reset).

useDelete(url, options)

Hook for DELETE requests.

function useDelete<T>(url: string, options?: UseHttpOptions<T>): UseHttpResult<T>
  • url — Request URL of the resource to delete.
  • options — HTTP request options including callbacks.

Returns: Request state (data, loading, error) and controls (execute, reset).

useLoggerProvider()

Hook to access the logger provider from context.

function useLoggerProvider(): LoggerProvider

Returns: The logger provider from context

useLogger(name, config)

Hook to get a logger instance.

function useLogger(name: string, config?: Partial<LoggerConfig>): Logger
  • name — Logger name (usually component or module name)
  • config — Optional logger configuration

Returns: Logger instance

useRootLogger()

Hook to get the root logger.

function useRootLogger(): Logger

Returns: Root logger instance

useChildLogger(parentName, context)

Hook to create a child logger with additional context.

function useChildLogger(parentName: string, context: Record<string, unknown>): Logger
  • parentName — Parent logger name
  • context — Additional context to include in logs

Returns: Child logger instance

useLogin()

Hook for login with async state tracking. Registration is available through const { register } = useAuth(); call register({ email, password, name }) to create an account. There is no separate useRegister hook. Use usePromise(register) when the form needs the same pending/error tracking as this login hook.

function useLogin<T = unknown>(): UseLoginReturn<T>

Returns: Login state and action

useOAuth(config)

Hook for OAuth authentication.

Reads OAuth configuration from the provided config and provides helpers to build OAuth URLs and start a login (full-page or popup). Automatically handles OAuth callbacks by detecting code and state URL parameters and exchanging them for a session — and, when the callback is running inside a popup we opened, relaying the result to the opener instead.

function useOAuth(config?: UseOAuthConfig): UseOAuthReturn
  • config — Optional OAuth configuration override (see UseOAuthConfig).

Returns: OAuth helpers: providers, getOAuthUrl, redirect, and loginViaPopup.

useOptimisticToggle(options)

Own the state and save ordering of a follow, favorite, star or subscription control while keeping all markup in the application. Pass toggle directly to the click handler: it takes no current/desired argument and computes the next value from the live controller. commit(desired) receives the value to SAVE, never the old value, and must return the server's boolean answer. Only the newest failure rolls back the displayed value.

Saves run one at a time; clicks during a save coalesce to the latest desired value. Use pending for feedback, not to disable the control or discard another click. Mount only after the initial record loads, key by record identity, and keep mounted during refetches. Keep authentication/permissions in the app. For a flag with a related count or other fields that must settle together, use useOptimisticValue with those fields in one value. A local UI switch without a server commit stays ordinary local state.

function useOptimisticToggle(options: UseOptimisticToggleOptions): UseOptimisticToggleResult
  • options — The server value, save adapter and optional error callback.

Returns: The displayed boolean, pending/error state and stable toggle() action.

useOptimisticValue(options)

A server-backed value — a favorite, follow, like or bookmark button, a rating, a quantity, a setting switch — that changes on the first render after a tap and is saved one change at a time, in order. Taps during a save update the desired value; the newest waiting value is saved after it (intermediate waiting values coalesce). Only a failure of the newest change puts the server value back. See createOptimisticValue in @molecule/app-state.

value is the server's value from props or a query. A new value is taken only when it differs (by equals) from the one the hook last received, and only while nothing is being saved, so a parent re-render or a refetch of older data never flips the button mid-save. The latest commit and onError are always used. Give the component a key per record, so one record's pending change never shows on another. Keep related fields, such as a favorite flag and its count, in the SAME value. Return both from the server response in commit, and publish that response to parent/query caches there if needed. Let commit reject on failure: a catch that returns old data hides the failure. Replace display-state setters and prop-copy effects with this hook's value and update. pending is for feedback, never a reason to disable the toggle or drop a tap.

Render/enable the keyed control only once its initial record exists. Keep that control mounted through refetches of the same record. This hook does not fix a click handler that returns on a still-null profile, or a remount that throws its controller away. Refetches during a save cannot replace pending intent; changed server snapshots arriving AFTER saving finishes are accepted and need query-layer ordering if they can be stale. See the module quickstart for a complete favorite button with a server-confirmed count.

function useOptimisticValue<T>(options: OptimisticValueOptions<T>): UseOptimisticValueResult<T>
  • options — The server's current value and how to save a change.

Returns: The value to render, whether a save is pending, the newest failure, and set/update.

usePasswordReset()

Hook for password reset flow with async state tracking.

Provides separate tracking for the request and confirm steps.

function usePasswordReset(): UsePasswordResetReturn

Returns: Password reset state and actions

usePlatform()

Hook for platform detection.

Uses module-level functions — platform is a singleton, not context-provided. Platform info is static and doesn't change at runtime, so this uses useMemo.

function usePlatform(): UsePlatformResult

Returns: Platform information and utility methods

usePreviewProvider()

Access the preview provider from context.

function usePreviewProvider(): PreviewProvider

Returns: The PreviewProvider instance from the nearest PreviewContext.

usePreview()

Hook for live preview management.

function usePreview(): UsePreviewResult

Returns: Preview state and controls: state (url, isLoading, device, error, isConnected), setUrl, refresh, setDevice, and openExternal.

useProfileForm(options)

Owns load → edit → submit → publish for the signed-in user's profile.

Same-account background updates refresh untouched fields but preserve dirty controls. Session ownership comes from the auth client, independently of mutable profile fields; an explicit getIdentity adds the caller's identity check. Submission snapshots the registered values before asynchronous validation, sends only changed fields through toPatch, and uses the auth client's configured updateProfile transport. The saved server response becomes the clean baseline; edits made while saving remain dirty. No request is made for a patch with no fields. A failed request retains the edits and shared user.

function useProfileForm<TUser, TValues extends FormValuesConstraint<TValues>>(
  options: UseProfileFormOptions<TUser, TValues>,
): UseProfileFormResult<TUser, TValues>
  • options — Controlled defaults, identity and wire adapters, optional cache/navigation callback.

Returns: Form state, typed control bindings, native submit binding and save error.

usePromise(asyncFn)

Hook that wraps an async function with state tracking.

For one UI action, pass state.status === 'pending' to Button loading from @molecule/app-ui-react (or to a native control's disabled prop). The control then refuses input while the request is pending and re-enables when the tracked call settles. Handle the returned promise's rejection; the hook also records the failure in state.error.

This hook tracks the latest call: it does not serialize invocations or cancel their network requests. An explicit reset/cancel changes the tracked state, so it is not proof that an outstanding request has stopped. Use an app-owned queue when every click must be accepted in order.

function usePromise<T, A extends unknown[]>(
  asyncFn: (...args: A) => Promise<T>,
): [UsePromiseState<T>, (...args: A) => Promise<T>]
  • asyncFn — The async function to wrap

Returns: Tuple of [state, wrappedFunction]

useRouterInstance()

Hook to access the router from context.

function useRouterInstance(): Router

Returns: The router from context

useLinkRouter(to)

Hook for the router a link to to navigates through: the mounted router, or null when to is a URL outside the app and none is mounted. The browser, or the device's URL handler, opens such a URL, so a link to it renders in a tree with no router (a widget, a static page). A link to an app path still fails without one: that is how an app that forgot to mount its router finds out.

Link uses it. Use it for a component of your own that follows a link's destination; Link's JSDoc gives the click rule such a component keeps.

function useLinkRouter(to: string): Router | null
  • to — The link's destination: an app path (/settings?tab=billing#plan) or a URL.

Returns: The mounted router, or null for a URL outside the app with no router mounted.

useRouter()

Hook for routing state and actions.

function useRouter(): UseRouterResult

Returns: Router state and navigation methods

useLocation()

Hook to get the current location.

function useLocation(): RouteLocation

Returns: The current route location

useParams()

Hook to get route parameters.

function useParams<T extends Record<string, string> = RouteParams>(): T

Returns: The current route parameters

useQuery()

Hook to get query parameters.

function useQuery<T extends QueryParams = QueryParams>(): T

Returns: The current query parameters

useNavigate()

Hook to get the navigate function.

function useNavigate(): (path: string, options?: NavigateOptions) => void

Returns: The navigate function

useIsActive(path, exact)

Hook to check if a path is active.

function useIsActive(path: string, exact?: boolean): boolean
  • path — The path to check
  • exact — Whether to match exactly (default: false)

Returns: Whether the path is active

useListRoute(options)

URL-backed pagination, filters and selected views, through whichever routing bond the app wired: the page, the filters and the view live in the URL only, so a reload, a shared link and Back all show the same list. Built on resolveListRoute from @molecule/app-routing, so every framework binding returns the same result.

A signed-out visit to a view with requiresAuth replaces the entry with options.auth.redirectTo, carrying state.returnTo; until auth is confirmed canLoad is false.

function useListRoute<Filter extends string = string, Selection extends string = string>(
  options?: ListRouteOptions<Filter, Selection>,
): ListRouteResult<Filter, Selection>
  • options — Filter sources, view paths, pagination and optional auth readiness.

Returns: The list state (page, offset, filters, selection, canLoad) and its link builder and navigation actions.

useConsumedSearchParam(name)

Takes a one-time credential (a reset token, an OAuth code) out of the URL and keeps it in memory, through whichever routing bond the app wired. The parameter is removed with a replace navigation that keeps the path, the hash, the other query values and the location state; the value survives re-renders and later query-only navigation, Back to an entry restores the value consumed there, and a new value arriving on the same mounted route is consumed too.

function useConsumedSearchParam(name: string): readonly [string, (value: string) => void]
  • name — The query key to consume, for example token or code.

Returns: The consumed value ('' before the parameter was ever present) and a setter (a form clears it after a successful submit).

useSignup()

Hook for user registration with async state tracking.

function useSignup<
  T = unknown,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(): UseSignupReturn<T, TRegister>

Returns: Signup state and action

useStorageProvider()

Hook to access the storage provider from context.

function useStorageProvider(): StorageProvider

Returns: The storage provider from context

useStorageValue(key, options)

Hook to manage a single storage value with React state sync.

function useStorageValue<T>(
  key: string,
  options?: UseStorageValueOptions<T>,
): UseStorageValueResult<T>
  • key — Storage key
  • options — Hook options

Returns: Storage value state (value, loading, error) and mutators (setValue, removeValue).

useStoragePreference(key, options)

Subscribes React state to ONE persisted preference.

This is the component-side half of getPreferenceStore(): a render-time value is available immediately when the bonded provider can answer synchronously, and an asynchronous provider's hydration CONVERGES onto the same component without a remount. Ordering is the store's: a read that started before a newer write, remove or external change is discarded, so a slow hydration never overwrites an edit the user already made.

Pass null for key while the real key is unknown (no project selected yet): the hook then behaves as local state around defaultValue and persists nothing.

function useStoragePreference<T = unknown>(
  key: string | null | undefined,
  options?: UseStoragePreferenceOptions<T>,
): UseStoragePreferenceResult<T>
  • key — The storage key, or null when there is nothing to persist.
  • options — defaultValue, reported until the provider supplies one.

Returns: The current value, its mutators, and whether it is definite yet.

useStorage()

Hook for simple storage operations without React state sync.

function useStorage(): {
  get: <T>(key: string) => Promise<T | null>
  set: <T>(key: string, value: T) => Promise<void>
  remove: (key: string) => Promise<void>
  clear: () => Promise<void>
  keys: () => Promise<string[]>
}

Returns: Storage operation methods

useStateProvider()

Hook to access the state provider from context.

The context comes from <StateProvider provider={…}> or from <MoleculeProvider> — which supplies the provider bonded under @molecule/app-state by default, so a scaffolded app needs no state prop.

Only hooks that read the context call this; useStore(store) takes its store as an argument and works with no provider at all.

function useStateProvider(): StateProvider

Returns: The state provider from context

useStore(store, options)

Hook to subscribe to a store with optional selector and equality function.

The store is the argument, so this hook needs NO StateProvider: it reads store.getState() and subscribes with store.subscribe(), and never touches the state context. A store minted outside the state bond — the direct createStoreWithActions() / createStore() a provider package exports — is therefore as valid here as one @molecule/app-state's createStore() made.

function useStore<T>(store: Store<T>, options?: UseStoreOptions<T, T>): T
  • store — The store to subscribe to
  • options — Hook options (selector, equalityFn)

Returns: The selected state

useSetStore(store)

Hook to get the store's setState function.

function useSetStore<T>(store: Store<T>): Store<T>['setState']
  • store — The store to get setState from

Returns: The setState function

useStoreAction(store, action)

Hook to create a bound action for a store.

function useStoreAction<T, Args extends unknown[], R>(
  store: Store<T>,
  action: (setState: Store<T>['setState'], getState: Store<T>['getState']) => (...args: Args) => R,
): (...args: Args) => R
  • store — The store to bind to
  • action — The action function that receives setState and getState

Returns: A bound action function

useThemeProvider()

Hook to access the theme provider from context.

function useThemeProvider(): ThemeProvider

Returns: The theme provider from context

useTheme()

Hook for theme state and actions.

function useTheme(): UseThemeResult

Returns: Theme state and actions

useCurrentTheme()

Hook to get just the current theme object.

function useCurrentTheme(): Theme

Returns: The current theme

useThemeMode()

Hook to get just the theme mode (light/dark).

function useThemeMode(): 'light' | 'dark'

Returns: The current theme mode

useThemeColors()

Hook to get theme colors.

function useThemeColors(): Theme['colors']

Returns: The current theme colors

useRichTranslation()

Reads rich catalog messages from the active provider. Call the returned translation function in render so it follows locale and catalog changes.

function useRichTranslation(): RichTranslateFunction

Returns: The locale-reactive rich translation function.

useI18nProvider()

Hook to access the i18n provider: the one the nearest I18nProvider supplies, otherwise the bonded @molecule/app-i18n provider, which is the one the static t reads. A component can therefore translate through useTranslation wherever the static t works, and it re-renders when the locale changes.

function useI18nProvider(): I18nProvider

Returns: The i18n provider from context, or the bonded provider.

useTranslation()

Hook for internationalization.

function useTranslation(): UseTranslationResult

Returns: Translation function and locale management

useT()

Hook to get just the translation function.

The returned function keeps ONE identity for as long as the provider instance is unchanged, so it is safe as an effect dependency: an effect written as useEffect(..., [t]) does not re-run on ordinary re-renders or on a locale change. The hook still re-renders the calling component on every locale notification (including addTranslations for the active locale), so text it reads while rendering is current. A value memoized on [t] alone keeps the old text after a locale switch: useMemo(() => t(...), [t]), or a React.memo child that receives t as a prop. Call useT() inside that child, or add useLocale() to the dependencies.

Call it in either of two compatible forms:

  • t(key, values?, options?) — the provider signature from @molecule/app-i18n, e.g. t('cart.total', { total }).
  • t(key, fallback, options?) — a shorthand for the common inline-English call: a string second argument is the defaultValue, so t('cart.empty', 'Your cart is empty') equals t('cart.empty', undefined, { defaultValue: 'Your cart is empty' }). Interpolation and pluralization still work: t('cart.items', '{{count}} items', { count: 3 }).
function useT(): UseTFunction

Returns: The translation function (stable identity while the provider is unchanged).

useLocale()

Hook to get the current locale.

function useLocale(): string

Returns: The current locale code

useDirection()

Hook to get the text direction.

function useDirection(): 'ltr' | 'rtl'

Returns: The text direction ('ltr' or 'rtl')

useI18nError(error)

Translates an error at render time so the displayed message updates automatically when the locale changes.

Always use this hook to display errors in React components — accessing error.message directly bypasses re-translation and leaves stale text after a locale switch. If error is an I18nError (thrown via throw new I18nError(key)), its key is translated using the current locale. For plain Error instances, error.message is returned unchanged.

function useI18nError(error: Error | null | undefined): string | null
  • error — The error to translate, or null/undefined.

Returns: The translated error string, or null if no error.

useVerifyPaymentReturn(options)

Reads the payment id a provider put in the return URL and confirms the purchase server-side with POST /users/:id/verify-payment/:provider.

This is why a hosted checkout returns the buyer to the APP and not the API. Session cookies are host-only on the app's origin, so a top-level redirect from the provider straight to an authenticated API callback on a different host arrives with NO credentials — it answers 401 and the paid plan is never granted. The request this hook makes is a same-origin call from a loaded app page, so the credentials apply. It waits for auth to hydrate first: after the redirect the page is a cold load, and the session is restored from the httpOnly cookie via GET /users/me.

Verification is idempotent server-side (first-claim-wins on the transaction), and this hook additionally runs at most once per transaction id per page. Safe on pages that are also reached normally: with no id in the URL it stays idle and issues no request.

If the component unmounts while the request is in flight, a verified purchase still refreshes the cached profile (the plan is paid for), but the hook calls neither onVerified nor onError and leaves the URL alone: by then the address may belong to another page. A failure after unmount is logged instead.

function useVerifyPaymentReturn(
  options?: UseVerifyPaymentReturnOptions,
): UseVerifyPaymentReturnResult
  • options — Provider fallback + lifecycle callbacks (see UseVerifyPaymentReturnOptions).

Returns: The verification state (see UseVerifyPaymentReturnResult).

useVersion()

Hook for version state and update actions.

Uses module-level getProvider() — version is a singleton, not context-provided.

function useVersion(): UseVersionResult

Returns: Version state and action methods

useWorkspaceProvider()

Access the workspace provider from context.

function useWorkspaceProvider(): WorkspaceProvider

Returns: The result.

useWorkspace()

Hook for IDE workspace layout management.

function useWorkspace(): UseWorkspaceResult

Returns: The workspace state and management methods.

StateProvider(props)

Provider for state management.

function StateProvider({ provider, children }: StateProviderProps): React.ReactElement
  • props — Component props (see StateProviderProps).

Returns: The rendered state provider element.

AuthProvider(props)

Provider for authentication.

function AuthProvider<T = unknown>({
  client,
  children,
  awaitSession = true,
  sessionFallback,
}: AuthProviderProps<T>): React.ReactElement
  • props — Component props (see AuthProviderProps).

Returns: The rendered auth provider element.

ThemeProvider(props)

Provider for theming.

function ThemeProvider({ provider, children }: ThemeProviderProps): React.ReactElement
  • props — Component props (see ThemeProviderProps).

Returns: The rendered theme provider element.

RouterProvider(props)

Provider for routing. A routing bond renders it for the app (the react-router bond's BrowserRouter does), so app code rarely mounts it by hand.

function RouterProvider({
  router,
  routedView,
  useRouteParams,
  children,
}: RouterProviderProps): React.ReactElement
  • props — Component props (see RouterProviderProps).

Returns: The rendered router provider element.

RoutedView()

Renders the matched child route, through whichever routing bond the app wired (React Router's Outlet under the react-router bond). A layout or guard used as a route element renders it where its page goes, so the component imports no router library.

function RoutedView(): React.ReactElement

Returns: The routing bond's routed view.

I18nProvider(props)

Provider for internationalization.

function I18nProvider({ provider, children }: I18nProviderProps): React.ReactElement
  • props — Component props (see I18nProviderProps).

Returns: The rendered i18n provider element.

HttpProvider(props)

Provider for HTTP client.

function HttpProvider({ client, children }: HttpProviderProps): React.ReactElement
  • props — Component props (see HttpProviderProps).

Returns: The rendered HTTP provider element.

StorageProvider(props)

Provider for storage.

function StorageProvider({ provider, children }: StorageProviderProps): React.ReactElement
  • props — Component props (see StorageProviderProps).

Returns: The rendered storage provider element.

LoggerProvider(props)

Provider for logging.

function LoggerProvider({ provider, children }: LoggerProviderProps): React.ReactElement
  • props — Component props (see LoggerProviderProps).

Returns: The rendered logger provider element.

WorkspaceProvider(props)

Provider for IDE workspace.

function WorkspaceProvider({ provider, children }: WorkspaceProviderProps): React.ReactElement
  • props — Component props (see WorkspaceProviderProps).

Returns: The rendered workspace provider element.

EditorProvider(props)

Provider for code editor.

function EditorProvider({ provider, children }: EditorProviderProps): React.ReactElement
  • props — Component props (see EditorProviderProps).

Returns: The rendered editor provider element.

PreviewProvider(props)

Provider for live preview.

function PreviewProvider({ provider, children }: PreviewProviderProps): React.ReactElement
  • props — Component props (see PreviewProviderProps).

Returns: The rendered preview provider element.

MoleculeProvider(props)

Combined provider for all molecule services.

Provides a convenient way to wrap your app with all molecule providers at once. Only providers that are passed will be included — except state, which falls back to the state provider bonded under @molecule/app-state (set by setupAllDefaultBonds() or a state bond) so useStore() works without a state prop.

function MoleculeProvider({
  children,
  state,
  auth,
  theme,
  router,
  i18n,
  http,
  storage,
  logger,
  workspace,
  editor,
  preview,
  awaitSession = true,
  sessionFallback,
}: MoleculeProviderProps): React.ReactElement
  • props — Component props (see MoleculeProviderProps) — each service is optional, and ONLY the services passed are provided to the tree.

Returns: The rendered combined provider element.

SessionReady(props)

Renders its children once useAuth().status has left 'loading' (signed in, signed out, or 'unavailable'), and fallback until then. It never redirects. An unavailable session is unconfirmed and may still have user === null; handle that status separately from sign-out.

With the bundled JWT client, a stored token AND cached user restore synchronously, so this boundary renders immediately. Token-only and cookie-only sessions need an asynchronous current-user request. Until it answers, useAuth().user is null, so a public page that renders a signed-in action at once lets that action run against "signed out": a Follow button whose handler starts with if (!user) return ignores the click, one that redirects to /login signs the visitor out of the flow. Wrapping the routes (or passing awaitSession to MoleculeProvider) makes every page's first render read the restored user when restoration succeeds.

A visitor with no session candidate settles synchronously without a request. Must render inside the auth context (AuthProvider, or MoleculeProvider with auth). A client that nobody initialized starts its restore on this first read. The bundled JWT client bounds each auth request (default 10 seconds) and settles a timeout as 'unavailable'. Custom clients must also settle their initial session status.

Synchronous SSR renders the fallback while a client is loading. Initialize a request-scoped client before rendering to include its decided content, or leave the hold disabled for SSR.

Route-level redirects for signed-in-only pages stay with AuthGuard (@molecule/app-ui-react).

function SessionReady({ children, fallback = null }: SessionReadyProps): ReactNode
  • props — SessionReadyProps.

Returns: The children once the session is decided, otherwise the fallback.

Constants

StateContext

Context for state management provider.

const StateContext: Context<StateProvider | null>

AuthContext

Context for authentication client.

const AuthContext: Context<AuthClient<unknown, Record<never, never>> | null>

ThemeContext

Context for theme provider.

const ThemeContext: Context<ThemeProvider | null>

RouterContext

Context for router.

const RouterContext: Context<Router | null>

I18nContext

Context for internationalization provider.

const I18nContext: Context<I18nProvider | null>

HttpContext

Context for HTTP client.

const HttpContext: Context<HttpClient | null>

StorageContext

Context for storage provider.

const StorageContext: Context<StorageProvider | null>

LoggerContext

Context for logger provider.

const LoggerContext: Context<LoggerProvider | null>

WorkspaceContext

Context for IDE workspace provider.

const WorkspaceContext: Context<WorkspaceProvider | null>

EditorContext

Context for code editor provider.

const EditorContext: Context<EditorProvider | null>

PreviewContext

Context for live preview provider.

const PreviewContext: Context<PreviewProvider | null>

Injection Notes

Requirements

Peer dependencies:

  • @molecule/app-keyboard ^1.0.1 (optional)
  • @molecule/app-lifecycle ^1.0.1 (optional)
  • @molecule/app-react ^5.0.0
  • react ^18.0.0 || ^19.0.0
  • react-native >=0.72.0 (optional)
  • react-native-safe-area-context >=4.0.0 (optional)

Runtime Dependencies

  • @molecule/app-keyboard (optional)

  • @molecule/app-lifecycle (optional)

  • @molecule/app-react

  • react

  • react-native (optional)

  • react-native-safe-area-context (optional)

  • The re-exported hooks keep @molecule/app-react's contract: each one throws unless its provider was passed to MoleculeProvider (or mounted individually). See the @molecule/app-react docs for the hook→provider map.

  • useSafeArea needs SafeAreaProvider (from react-native-safe-area-context) mounted at the root; without it — or without the library installed — it silently returns zero insets rather than throwing, so a notch-overlapped header means missing provider, not a bug in the hook.

  • useBackHandler only fires on Android; iOS has no hardware back button.

  • For components/styling pair this with @molecule/app-ui-react-native, whose ClassMap styling requires the NativeWind setup (@molecule/app-ui-nativewind) — see that package's docs.

Use @molecule/app-react-native/chat, @molecule/app-react-native/ai-models, and @molecule/app-react-native/push for those features.