# Docs ## Frequently Asked Questions (FAQ) ### How is Relay different from chaining `useEffect` hooks? `useEffect` excels at responding to prop/state changes, but it doesn’t encode the idea of a sequential flow with typed payloads or single-line navigation. Relay stores each step in a typed store, tracks its status, and exposes helpers like `start`, `retry`, and `next`. That means you can declaratively rerun the second step without coupling it to every state variable that the first step mutates. ### Can Relay run outside of React (e.g., in a Node script)? Relay ships as ESM and only depends on TypeScript-friendly helpers, so you can use `createRelay` in Node.js to orchestrate background jobs or CLI flows. See the Node.js example at `/docs/examples/nodejs` for a non-React script that initializes a relay, starts the flow, and logs every step’s status as it runs. ### When should I use `retry` vs `initialize`? Use `retry` when you want to re-run the failed step with the same arguments—Relay retains the current `steps` array and lets you re-execute the step that set `relay.isErrored`. Call `initialize` when you want to swap in a completely new sequence (for example, moving from a signup flow to an onboarding flow) so the store resets and begins from step one. ### Where can I inspect working Relay flows? The `apps/examples.relay` Next.js demo wires `createRelay("relay-example")` into a page (`apps/examples.relay/src/app/page.tsx`). It’s a good reference for hooking Relay into React 18 server/client components, and the docs pages under `apps/docs.relay/pages/docs/examples/` show simplified snippets you can copy/paste. ## Getting Started Before starting, note that `Relay` is typed from the ground up. The `createRelay` factory defined in `libraries/relay/src/relay.ts` lets you parametrize the configuration, step metadata, success payload, and error payload types before you register any steps. Type every shape first, then rely on `StepSuccess` and `StepError` to keep the runtime results discriminated so the compiler knows exactly when a step succeeded or failed. The rest of this guide walks you through that flow. :::steps ### Declare your `config` The first step is to define the TypeScript shapes that the relay will enforce. At a minimum, specify: * `RelayConfig`: extends the default Relay configuration. * `RelayStepBase`: carries metadata shared between every step. * `RelayStepSuccess`: represents the payload returned when a step resolves successfully. * `RelayStepError`: represents the payload returned when a step fails. ```ts filename="config.ts" type RelayConfig = {}; type RelayStepBase = { label: string; }; type RelayStepTransactionSuccess = { type: "transaction"; txHash: string; blockNumber: number; }; type RelayStepApiCallSuccess = { type: "apicall"; }; type RelayStepSuccess = RelayStepTransactionSuccess | RelayStepApiCallSuccess; type RelayStepError = { message: string; }; ``` These types keep your configuration options, step metadata, success payloads, and error payloads explicit so the rest of your app consumes typed data. Everything is fully typed. ### Instantiate the Relay and export helpers With the types in place, call `createRelay` and pass the generics so the returned helpers stay typed across your app. Doing so wires the store with your `StepSuccess` and `StepError` payload shapes and makes it easy to reuse `myRelay` from any component. ```ts // [!include config.ts] const myRelay = createRelay("my-relay"); // [!code focus] export { myRelay }; // [!code focus] ``` This gives you a singleton keyed by `my-relay` with your configurations. ### Create the steps Where you define your steps is flexible: you can build them inside a hook or in a standalone module, whichever fits your architecture. In most apps you will set them up while preparing the UI (typically in a hook). Below we create three placeholder steps to demonstrate the shape. ```tsx filename="app.tsx" // [app.tsx] const steps = [ myRelay.createRelayStep({ id: "id-0", label: "API call", fn: async () => { await new Promise((resolve) => setTimeout(resolve, 1000)); return myRelay.StepSuccess({ type: "apicall" }); }, }), myRelay.createRelayStep({ id: "id-1", label: "Send Tx", fn: async () => { await new Promise((resolve) => setTimeout(resolve, 1000)); return myRelay.StepSuccess({ type: "transaction", txHash: "0x", blockNumber: 100_000_000, }); }, }), myRelay.createRelayStep({ id: "id-2", label: "API call", fn: async () => { await new Promise((resolve) => setTimeout(resolve, 1000)); return myRelay.StepSuccess({ type: "apicall" }); }, }), ]; ``` These step definitions now exist and are fully typed. ### Initialize the Relay with the steps Calling `initialize` stores the steps in memory so they are ready to fire and execute. ```tsx filename="app.tsx" // [app.tsx] const App = () => { const { initialize } = myRelay.useRelay(); return (
); }; ``` ### Start the Relay Starting the relay executes the initialized steps in order. ```tsx filename="app.tsx" // [app.tsx] const App = () => { const { start } = myRelay.useRelay(); return (
); }; ``` ### Observe The final step is observing the relay state and inspecting each step’s status. ```tsx filename="sidebar.tsx" // [sidebar.tsx] const Sidebar = () => { const { stepsBase, stepsState } = myRelay.useRelay(); return (
{stepsBase.map((item, index) => { const state = stepsState[index]; return (
{item.label}
{(() => { if (state.status === "success") { const payload = state.payload; if (payload.type === "apicall") { return
Success
; } if (payload.type === "transaction") { return (
{payload.txHash}
{payload.blockNumber}
); } } if (state.status === "error") { return
{state.payload.message}
; } return
{state.status}
; })()}
); })}
); }; ``` ::: Because the `steps` share the metadata and payload types defined in `libraries/relay/src/relay.ts`, the entire pipeline stays strongly typed. The `relay.initialize`/`relay.start` pair wires the flow and begins execution. After that you can use `relay.retry()` to rerun a failed step or `relay.next()` to advance manually while keeping an eye on `relay.stepsState` for the live statuses. Now your pipeline is wired: the typed store owns the state, your component creates typed steps, and the UI executes them through the Relay helpers. ## Installation Relay is published as `@0xhq/relay` and ships as ESM. Make sure your project declares `"type": "module"` or uses a bundler that understands `.ts/.mjs` outputs. ### Add the package :::code-group ```bash [pnpm] pnpm add @0xhq/relay ``` ```bash [npm] npm install @0xhq/relay ``` ```bash [yarn] yarn add @0xhq/relay ``` ::: ### Verify your toolchain * **TypeScript projects** should keep `moduleResolution` set to `node16`/`nodenext` so the exported `.ts` entry points resolve correctly. * **Frameworks (Next.js, Astro, etc.)** usually support ESM bundles out of the box, but confirm the build output can resolve `.ts` sources from `node_modules`. * Relay has no runtime peer dependencies beyond React (if you use `useRelay` in components), but you will need to polyfill `fetch` or `crypto` in environments that lack them (e.g., older Node.js versions). ## Why Relay `React` makes building event-driven UIs easy, but `coordinating` multi-step `flows—forms`, `payments`, `blockchain transactions` or anything async, quickly turns into tangled `useEffect` chains, manual timers, or duplicated state. Relay was created to give those flows an `explicit structure`: each step is a `typed` operation, `Relay` keeps status and payload data in a Zustand-backed `store`, and the UI can drive navigation with helpers instead of ad-hoc callbacks. ### Relay at a glance * **Typed steps** declare their `success` and `error` payloads. * **Flows** are ordered step sequences that `Relay` executes one by one. * **Stores** live per `createRelay` key and expose `selectors` and `helpers`. * **Status tracking** surfaces operation `states`. *** Relay is intentionally `un-opinionated` about how you build your steps while still giving you atomic control over each transition. ## Node.js example Relay runs just as well in CLI scripts as it does inside React. This example uses `createRelay` in a Node process to initialize three sequential steps, starts the flow, and polls the store so the script can log the current status of every step as it resolves. #### Run it ```bash pnpm dlx tsx apps/docs.relay/examples/nodejs/run.ts ``` You can swap `tsx` for `ts-node` or another TypeScript runner if that’s what your environment already uses. The key is the same: load the steps, call `relay.start()`, and read `relay.getState()` to inspect `stepsState`, capability guards, and the final payloads. #### Script ```ts // [!include ~/examples/nodejs/run.ts] ``` import { SimpleExample } from "../../../examples/simple"; ## Simple example The simple example shows how to wire up a basic Relay layout with a header, sidebar, and footer so you can see how the pieces fit together before customizing anything. It pulls in the sample `SimpleExample` component along with the related layout fragments below, which together demonstrate the standard structure for a Relay application page. ### relays.ts ```ts // [!include ~/examples/simple/relays.ts] ``` ### index.tsx ```ts // [!include ~/examples/simple/index.tsx] ``` ### header.tsx ```ts // [!include ~/examples/simple/header.tsx] ``` ### sidebar.tsx ```ts // [!include ~/examples/simple/sidebar.tsx] ``` ### app.tsx ```ts // [!include ~/examples/simple/app.tsx] ``` ### footer.tsx ```ts // [!include ~/examples/simple/footer.tsx] ```