# React hooks

> How to run a ceremony from a React client component, with the @esigncomply/react hooks or with the browser SDK directly.

Source: https://esigncomply.com/docs/sdk/react

`@esigncomply/react` is a thin layer of hooks over the [browser SDK](https://esigncomply.com/docs/sdk/browser.md). It ships no visual components: you build every element of the signing screen, and the hooks connect those elements to the ceremony.

```bash
npm install @esigncomply/react @esigncomply/browser
```

`react` (18 or later) and `@esigncomply/browser` are peer dependencies. The package is an ES module with type declarations. Its built file starts with `"use client"`, so the hooks run in the browser only.

## What the package contains

| Export | Kind | Purpose |
|---|---|---|
| `useCeremony` | Hook | Attaches to one session by its client token and follows it: status, outstanding steps, findings, the last error. |
| `useDocument` | Hook | Reports the presentation of one pinned document version for an element you render. |
| `EsignComplyError` | Class | The error class of the browser SDK, exported again so `instanceof` works without a second import. |
| `CeremonyStatus`, `UseCeremonyOptions`, `UseCeremonyResult`, `UseDocumentOptions`, `UseDocumentResult` | Types | The hook signatures, described below. |
| `Ceremony`, `CompleteResult`, `Finding`, `PresentationMode`, `StepResult` | Types | Exported again from `@esigncomply/browser`. |

```ts
import { useCeremony, useDocument, EsignComplyError } from "@esigncomply/react";
import type { Ceremony, CeremonyStatus, UseCeremonyResult, UseDocumentResult } from "@esigncomply/react";
```

Both hooks call the browser SDK. Everything on the [browser SDK](https://esigncomply.com/docs/sdk/browser.md) page applies: the methods of the `ceremony` object, the events each one records, the errors, and the requirements.

> **Never.** Do not import `esigncomply` (the server package) or read `ESIGNCOMPLY_API_KEY` in a file marked `"use client"`. The browser receives the session client token (`esc_ct_...`) and nothing else.

## useCeremony

```ts
function useCeremony(options: UseCeremonyOptions): UseCeremonyResult;

interface UseCeremonyOptions {
  clientToken: string | null | undefined;
  apiUrl?: string;
}

interface UseCeremonyResult {
  ceremony: Ceremony | null;
  status: CeremonyStatus;
  remainingSteps: string[];
  findings: Finding[];
  error: EsignComplyError | null;
  canComplete: boolean;
}

type CeremonyStatus = "idle" | "attaching" | "ready" | "error" | "completed";
```

| Option | Description |
|---|---|
| `clientToken` | The session client token from your server. While it is `null`, `undefined` or empty, the hook stays `idle` and attaches nothing. |
| `apiUrl` | The `api_url` of the session your server created. Pass it for sessions outside the US region. |

The hook calls `EsignComply.attach({ clientToken, apiUrl })` in an effect and returns:

| Field | Description |
|---|---|
| `ceremony` | The attached `Ceremony` from `@esigncomply/browser`, or `null` until the attach has resolved. |
| `status` | `idle`: no token yet. `attaching`: the attach is running. `ready`: attached. `error`: the attach failed or the session expired. `completed`: the signing act was recorded. |
| `remainingSteps` | The steps still outstanding, from `ceremony.remainingSteps()`. It follows the page: unticking the box puts `intent.captured` back. Empty until the ceremony is ready. |
| `findings` | Conformance findings that did not pass, the latest for each step. A new result for a step replaces the earlier findings of that step. Each has `rule`, `status`, `message`, `fix` and `doc_url`. |
| `error` | The reason the attach failed, or the last error a ceremony method raised, as an `EsignComplyError` with `code`, `rule` and `fix`. `null` when there is none. After the session expires it is an error with code `client_token_expired`. |
| `canComplete` | `true` when `status` is `ready` and `signature.applied` is the only step left. Use it to enable the action control. |

How the hook attaches:

- **Once per session.** One attachment exists per pair of `clientToken` and `apiUrl`. Every component that calls `useCeremony` with the same pair shares it and gets the same `ceremony` object.
- **Strict mode.** In development React runs effects twice. The session is still attached once, and `client.attached` is recorded once.
- **Cleanup.** The ceremony is destroyed when the last component that uses the token unmounts. You do not call `ceremony.destroy()` yourself.
- **Retry.** A failed attach is forgotten, so a later mount with the same token tries again.
- **A method error does not change `status`.** A rejected `presentDocument` or `complete` sets `error` and leaves `status` at `ready`. Only a failed attach or an expired session sets `status` to `error`.

## useDocument

```ts
function useDocument<T extends Element = HTMLElement>(
  ceremony: Ceremony | null | undefined,
  options: UseDocumentOptions,
): UseDocumentResult<T>;

interface UseDocumentOptions {
  versionId: string | null | undefined;
  mode: PresentationMode; // "hyperlink" | "inline" | "scrollbox"
}

interface UseDocumentResult<T extends Element> {
  ref: (element: T | null) => void;
  presented: boolean;
  error: EsignComplyError | null;
}
```

| Parameter | Description |
|---|---|
| `ceremony` | The `ceremony` from `useCeremony`. While it is `null` the hook waits. |
| `versionId` | A document version pinned on the session (`documents[].version_id` of the session your server created). While it is empty the hook waits. |
| `mode` | `hyperlink`: put `ref` on the link. `inline` or `scrollbox`: put `ref` on the element that holds the document text. |

| Field | Description |
|---|---|
| `ref` | A callback ref. It goes on the link or on the container. |
| `presented` | `true` once `document.presented` is recorded for this version. |
| `error` | The `EsignComplyError` of a presentation that failed, or `null`. |

Once the ceremony, the element and the version ID all exist, the hook calls `ceremony.presentDocument({ versionId, mode, link })` for a hyperlink, or `ceremony.presentDocument({ versionId, mode, container })` for the other two modes. The browser SDK treats the same element and version as one presentation, so a strict-mode rerun sends nothing twice. For a download or print control, mark it with `data-esc-download` or `data-esc-print` inside the container or on the linked document page.

Every other step is a method on `ceremony`: `observeAssent`, `verify.start`, `verify.confirm`, `verify.passkey`, `presentDisclosure`, `reviewPresented`, `complete`, `cancel` and the rest. Call them from effects and event handlers.

## Rules for React components

- **Client only.** Call the hooks in a file marked `"use client"`. They attach in an effect, never during render.
- **Start when the form mounts.** Render the form with the client token already in its props, so the ceremony attaches before the signer acts. Do not attach on submit.
- **Refs, not selectors.** Pass DOM elements from refs. Call ceremony methods after the elements are mounted.
- **Do not drive the controls.** Every checkbox starts unchecked and every typed-name field starts empty. Leave the checkbox uncontrolled, or control it with state that starts `false`. Never set `checked`, call `.click()` or submit on the user's behalf. The SDK reports the control as it finds it ([CR-01](https://esigncomply.com/docs/conformance.md#cr-01)).
- **Disable, do not hide.** Keep the action button disabled until `canComplete` is `true`.
- **Confirm on the server.** The result of `ceremony.complete()` is delivered to the browser. Grant access only after your server has confirmed the record. See [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md).

## Signup form example

The parent server component, or a server action, creates the session with the [Node SDK](https://esigncomply.com/docs/sdk/node.md) and passes four values down: `clientToken`, `apiUrl` and the two pinned version IDs. The form runs an L1 ceremony with a checkbox and a button. `finishSignup` is your server action. It confirms the record with the secret key before it creates the account.

```tsx
"use client";

import { useEffect, useRef, useState, type FormEvent } from "react";
import { EsignComplyError, useCeremony, useDocument } from "@esigncomply/react";
import { finishSignup } from "./actions"; // server action: (form: FormData, recordId: string) => Promise<void>

type Props = { clientToken: string; apiUrl: string; tosVersionId: string; privacyVersionId: string };

export function SignupForm({ clientToken, apiUrl, tosVersionId, privacyVersionId }: Props) {
  const { ceremony, status, error, canComplete } = useCeremony({ clientToken, apiUrl });
  const tos = useDocument<HTMLAnchorElement>(ceremony, { versionId: tosVersionId, mode: "hyperlink" });
  const privacy = useDocument<HTMLAnchorElement>(ceremony, { versionId: privacyVersionId, mode: "hyperlink" });

  const assentRef = useRef<HTMLDivElement>(null);
  const checkboxRef = useRef<HTMLInputElement>(null);
  const submitRef = useRef<HTMLButtonElement>(null);
  const [message, setMessage] = useState<string | null>(null);
  const [pending, setPending] = useState(false);

  // Observe the assent controls once both documents are presented.
  // A failure reaches the hook's `error`, so the returned promise needs no handler here.
  useEffect(() => {
    if (!ceremony || !tos.presented || !privacy.presented) return;
    void ceremony.observeAssent({
      region: assentRef.current, // notice, links, checkbox, button
      checkbox: checkboxRef.current,
      submit: submitRef.current,
    });
  }, [ceremony, tos.presented, privacy.presented]);

  // The signing act, from the signer's real click.
  async function onSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (!ceremony) return;
    const form = new FormData(event.currentTarget);
    setPending(true);
    setMessage(null);
    try {
      const result = await ceremony.complete(); // { recordId, receipt, verifyUrl, status }
      await finishSignup(form, result.recordId);
    } catch (err) {
      // A refusal (4xx, or one made in the browser) carries a message and a fix: keep the form.
      // Anything else is inconclusive: never proceed without a confirmed record.
      const refused = err instanceof EsignComplyError && err.code !== "network_error" && err.status < 500;
      setMessage(refused ? err.message : "We could not confirm whether your acceptance was recorded. Please wait while we check.");
    } finally {
      setPending(false);
    }
  }

  const shown =
    message ??
    (status === "error" ? "We could not start the signing step. Reload the page to try again." : null) ??
    tos.error?.message ??
    privacy.error?.message ??
    error?.message ??
    null;

  return (
    <form onSubmit={onSubmit}>
      <label htmlFor="email">Email</label>
      <input id="email" name="email" type="email" autoComplete="email" required />

      <div ref={assentRef}>
        <p>
          By checking the box and clicking Create account, you agree to the{" "}
          <a ref={tos.ref} href="/legal/terms">Terms of Service</a> and acknowledge the{" "}
          <a ref={privacy.ref} href="/legal/privacy">Privacy Notice</a>.
        </p>
        <label>
          <input ref={checkboxRef} type="checkbox" name="agree" /> I agree to the Terms of Service and Privacy Notice
        </label>
        <button ref={submitRef} type="submit" disabled={!canComplete || pending}>
          Create account
        </button>
      </div>

      {shown ? <p role="alert">{shown}</p> : null}
    </form>
  );
}
```

What the example relies on:

- The checkbox is uncontrolled and has no `defaultChecked`. It starts unchecked and only the user changes it.
- The notice, both links, the checkbox and the button sit inside the one element passed as `region`. Nothing sits between the notice and the button.
- The links point at document pages on your own domain that render the registered version inside `<article data-esc-document>`. See the [Next.js guide](https://esigncomply.com/docs/guides/nextjs.md).
- `canComplete` turns true when the documents and the notice are recorded and the box is ticked. If the user unticks the box, the button is disabled again.
- A rejected call carries a rule ID and a `fix`. In test mode the SDK also logs both to the browser console. During development you can render `findings` from `useCeremony` to see each rule, message and fix on the page.

## Typed-name signatures

For an NDA or a contract, pass an empty text field instead of a checkbox. The name leaves the page once, with the signing act.

```tsx
const nameRef = useRef<HTMLInputElement>(null);

useEffect(() => {
  if (!ceremony || !nda.presented) return;
  void ceremony.observeAssent({ region: assentRef.current, typedName: nameRef.current, submit: submitRef.current });
}, [ceremony, nda.presented]);

// <input ref={nameRef} type="text" name="legal_name" autoComplete="off" />   (no defaultValue, no value prop)
```

Here `nda` is the result of `useDocument` for the document being signed. Do not prefill the field from the account profile, and do not render the name in a cursive font as the signature. For email verification before signing, call `ceremony.verify.start()` and `ceremony.verify.confirm()` from your own buttons: see [L2 verification](https://esigncomply.com/docs/guides/l2-verification.md).

## Without the hooks

The hooks are optional. `@esigncomply/browser` works in a client component on its own: call `EsignComply.attach()` inside `useEffect`, keep the ceremony in state, subscribe to `change` to track `remainingSteps()`, and call `destroy()` in the cleanup. In strict mode guard the async attach with a flag and destroy a ceremony that resolves after cleanup. The methods are on the [browser SDK](https://esigncomply.com/docs/sdk/browser.md) page.

## Server components and server actions

Keep three things on the server: the secret key, session creation, and confirmation of the record. A typical split in the Next.js App Router:

| Piece | Where | Uses |
|---|---|---|
| Create the session | Server action or route handler | `esigncomply`, `ESIGNCOMPLY_API_KEY` |
| Run the ceremony | Client component | `@esigncomply/react` or `@esigncomply/browser`, the client token |
| Confirm the record and grant access | Server action or webhook route | `esigncomply`, `ESIGNCOMPLY_API_KEY` |

The full walkthrough, including the Supabase table and the webhook, is in the [Next.js guide](https://esigncomply.com/docs/guides/nextjs.md).
