Guides
State outside the form
Learn how to keep the form values outside the form to show a live summary.
Initial steps
We'll show you how to keep the form values outside the form, so they're always available as users type. To follow along, start by cloning the repository below, which is our starting point.
git clone https://github.com/martiserra99/formity-state-outside-the-form
Then install the dependencies.
npm install
The repo is a React project using Vite and TypeScript, with @formity/react already installed for you. It contains a four-step checkout form built with React Hook Form, and a summary panel.
Before we start
Before changing anything, let's look at the code we start from. There are three files that we'll update, and the rest of the repo stays as it is.
The first one is src/components/form/index.tsx, with the Form component.
// src/components/form/index.tsx
import type { DefaultValues, Resolver } from "react-hook-form";
import type { Back, Next } from "@formity/react";
import { useForm, FormProvider } from "react-hook-form";
import type { FormStatus } from "@/types/status";
import { ItemView, type Item } from "./item";
import { Button } from "../button";
interface FormProps<T extends Record<string, unknown>> {
defaultValues: DefaultValues<T>;
resolver: Resolver<T>;
heading: string;
message: string;
content: Item[];
buttons: {
back: string | null;
next: string;
};
back: Back<T>;
next: Next<T>;
status: FormStatus;
}
export function Form<T extends Record<string, unknown>>({
defaultValues,
resolver,
heading,
message,
content,
buttons,
back,
next,
status,
}: FormProps<T>) {
const form = useForm({ defaultValues, resolver });
return (
<form noValidate autoComplete="off" onSubmit={form.handleSubmit(next)}>
<FormProvider {...form}>
<div className="mb-8">
<h2 className="mb-1.5 text-2xl font-bold text-gray-950">{heading}</h2>
<p className="text-sm font-medium text-gray-400">{message}</p>
</div>
<div className="@container mb-8 flex flex-col gap-6">
{content.map((item, i) => (
<ItemView key={i} {...item} />
))}
</div>
<div className="flex w-full items-center justify-end gap-4">
{buttons.back && (
<Button
type="button"
variant="secondary"
disabled={status.submitting}
onClick={() => back(form.getValues())}
>
{buttons.back}
</Button>
)}
<Button type="submit" variant="primary" disabled={status.submitting}>
{status.submitting ? "Submitting..." : buttons.next}
</Button>
</div>
</FormProvider>
</form>
);
}
Each field in content is described by an Item object and rendered by the ItemView component. The status prop tells the form whether it's being submitted, through its submitting property.
The second one is src/flow.tsx, which contains the Schema and the flow.
// src/flow.tsx
import type { UnionToIntersection } from "type-fest";
import type { Flow, s } from "@formity/react";
import type { FormStatus } from "./types/status";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Form } from "./components/form";
import * as constants from "./constants";
type Values = UnionToIntersection<Fields[keyof Fields]>;
type Fields = {
contact: {
firstName: string;
lastName: string;
email: string;
};
shipping: {
address: string;
city: string;
postalCode: string;
country: string;
};
delivery: {
deliveryMethod: string;
};
payment: {
cardholderName: string;
cardNumber: string;
expiryDate: string;
};
};
export type Schema = {
render: React.ReactNode;
struct: [
s.Form<Fields["contact"]>,
s.Form<Fields["shipping"]>,
s.Form<Fields["delivery"]>,
s.Form<Fields["payment"]>,
s.Return<Values>,
];
inputs: Record<never, never>;
params: {
status: FormStatus;
};
};
export const flow: Flow<Schema> = [
{
form: {
fields: () => ({
firstName: ["", []],
lastName: ["", []],
email: ["", []],
}),
render: ({ fields, params, back, next }) => (
<Form
key="contact"
defaultValues={fields}
resolver={zodResolver(
z.object({
firstName: z.string().nonempty("Please enter your first name"),
lastName: z.string().nonempty("Please enter your last name"),
email: z.email("Please enter a valid email address"),
}),
)}
heading="Contact"
message="We'll send your order confirmation here."
content={[
{
type: "columns",
columns: [
{
type: "input",
name: "firstName",
label: "First name",
placeholder: "Jane",
},
{
type: "input",
name: "lastName",
label: "Last name",
placeholder: "Smith",
},
],
},
{
type: "input",
name: "email",
label: "Email address",
placeholder: "jane@example.com",
inputType: "email",
},
]}
buttons={{ back: null, next: "Continue" }}
back={back}
next={next}
status={params.status}
/>
),
},
},
{
form: {
fields: () => ({
address: ["", []],
city: ["", []],
postalCode: ["", []],
country: ["", []],
}),
render: ({ fields, params, back, next }) => (
<Form
key="shipping"
defaultValues={fields}
resolver={zodResolver(
z.object({
address: z.string().nonempty("Please enter your address"),
city: z.string().nonempty("Please enter your city"),
postalCode: z.string().nonempty("Please enter your postal code"),
country: z.string().nonempty("Please select your country"),
}),
)}
heading="Shipping address"
message="Where should we deliver your order?"
content={[
{
type: "input",
name: "address",
label: "Address",
placeholder: "123 Main St",
},
{
type: "columns",
columns: [
{
type: "input",
name: "city",
label: "City",
placeholder: "New York",
},
{
type: "input",
name: "postalCode",
label: "Postal code",
placeholder: "10001",
},
],
},
{
type: "select",
name: "country",
label: "Country",
placeholder: "Select a country",
options: constants.countries,
},
]}
buttons={{ back: "Back", next: "Continue" }}
back={back}
next={next}
status={params.status}
/>
),
},
},
{
form: {
fields: () => ({
deliveryMethod: ["", []],
}),
render: ({ fields, params, back, next }) => (
<Form
key="delivery"
defaultValues={fields}
resolver={zodResolver(
z.object({
deliveryMethod: z
.string()
.nonempty("Please select a delivery method"),
}),
)}
heading="Delivery method"
message="Choose how fast you'd like your order to arrive."
content={[
{
type: "radio",
name: "deliveryMethod",
options: constants.deliveryMethods.map((m) => ({
value: m.value,
label: m.label,
description: m.description,
priceLabel: m.priceLabel,
})),
},
]}
buttons={{ back: "Back", next: "Continue" }}
back={back}
next={next}
status={params.status}
/>
),
},
},
{
form: {
fields: () => ({
cardholderName: ["", []],
cardNumber: ["", []],
expiryDate: ["", []],
}),
render: ({ fields, params, back, next }) => (
<Form
key="payment"
defaultValues={fields}
resolver={zodResolver(
z.object({
cardholderName: z
.string()
.nonempty("Please enter the cardholder name"),
cardNumber: z.string().nonempty("Please enter your card number"),
expiryDate: z.string().nonempty("Please enter the expiry date"),
}),
)}
heading="Payment"
message="Your payment information is encrypted and secure."
content={[
{
type: "input",
name: "cardholderName",
label: "Cardholder name",
placeholder: "Jane Smith",
},
{
type: "cardNumber",
name: "cardNumber",
label: "Card number",
},
{
type: "expiryDate",
name: "expiryDate",
label: "Expiry date",
},
]}
buttons={{ back: "Back", next: "Place order" }}
back={back}
next={next}
status={params.status}
/>
),
},
},
{
return: (values) => values,
},
];
The Values type combines the fields of the four steps into a single object. It takes the union of the step types with Fields[keyof Fields], and merges them with UnionToIntersection.
The third one is src/app.tsx, which renders the form next to the summary.
// src/app.tsx
import type { OnReturn, ReturnOutput } from "@formity/react";
import type { Status, FormStatus } from "./types/status";
import { useState, useCallback } from "react";
import { useFormity } from "@formity/react";
import { Summary } from "./components/summary";
import { Done } from "./components/done";
import { flow, type Schema } from "./flow";
export default function App() {
const [status, setStatus] = useState<Status<ReturnOutput<Schema>>>({
type: "form",
submitting: false,
});
const onReturn = useCallback<OnReturn<Schema>>(async (output) => {
setStatus({ type: "form", submitting: true });
// Show output in the console
console.log(output);
// Simulate a network request
await new Promise((resolve) => setTimeout(resolve, 1000));
setStatus({ type: "done", output });
}, []);
if (status.type === "done") {
return (
<Done
output={status.output}
onStartOver={() => setStatus({ type: "form", submitting: false })}
/>
);
}
return <Form status={status} onReturn={onReturn} />;
}
interface FormProps {
status: FormStatus;
onReturn: OnReturn<Schema>;
}
function Form({ status, onReturn }: FormProps) {
const form = useFormity({
flow,
params: { status },
onReturn,
});
return (
<div className="flex h-screen w-full overflow-hidden bg-white">
<main className="flex flex-1 items-start justify-center overflow-y-auto px-6 py-12">
<div className="w-full max-w-lg">{form}</div>
</main>
<Summary
values={{
email: "",
city: "",
country: "",
deliveryMethod: "",
}}
/>
</div>
);
}
For now the Summary component receives empty strings, so it doesn't show any of the form values. We can't pass them yet, since the values of a step stay inside its Form until it's submitted.
Watching changes
The summary must update as users type, but Formity only receives a step's values when it's submitted. So we'll keep the values in a state of the parent, updated on every change.
We need to update the Form component, since it knows when a field changes. It receives the values of all the steps in values, and on every change it calls onValuesChange with them updated.
We also add a type parameter to type the new props. T is the type of the fields of the step, and U is the type of the values of all the steps, which include those fields.
// src/components/form/index.tsx
import type { DefaultValues, Resolver } from "react-hook-form";
import type { Back, Next } from "@formity/react";
import { useForm, FormProvider } from "react-hook-form";
import { useEffect, useEffectEvent } from "react";
import type { FormStatus } from "@/types/status";
import { ItemView, type Item } from "./item";
import { Button } from "../button";
interface FormProps<T extends Record<string, unknown>, U extends T> {
defaultValues: DefaultValues<T>;
resolver: Resolver<T>;
heading: string;
message: string;
content: Item[];
buttons: {
back: string | null;
next: string;
};
back: Back<T>;
next: Next<T>;
status: FormStatus;
values: U;
onValuesChange: (values: U) => void;
}
export function Form<T extends Record<string, unknown>, U extends T>({
defaultValues,
resolver,
heading,
message,
content,
buttons,
back,
next,
status,
values,
onValuesChange,
}: FormProps<T, U>) {
const form = useForm({ defaultValues, resolver });
const onFieldsChange = useEffectEvent(({ values: fields }: { values: T }) => {
onValuesChange({ ...values, ...fields });
});
useEffect(() => {
return form.subscribe({
formState: { values: true },
callback: onFieldsChange,
});
}, [form]);
return (
<form noValidate autoComplete="off" onSubmit={form.handleSubmit(next)}>
<FormProvider {...form}>
<div className="mb-8">
<h2 className="mb-1.5 text-2xl font-bold text-gray-950">{heading}</h2>
<p className="text-sm font-medium text-gray-400">{message}</p>
</div>
<div className="@container mb-8 flex flex-col gap-6">
{content.map((item, i) => (
<ItemView key={i} {...item} />
))}
</div>
<div className="flex w-full items-center justify-end gap-4">
{buttons.back && (
<Button
type="button"
variant="secondary"
disabled={status.submitting}
onClick={() => back(form.getValues())}
>
{buttons.back}
</Button>
)}
<Button type="submit" variant="primary" disabled={status.submitting}>
{status.submitting ? "Submitting..." : buttons.next}
</Button>
</div>
</FormProvider>
</form>
);
}
React Hook Form's subscribe function calls onFieldsChange whenever a field of the step changes. The same idea fits any form library, as long as it lets you listen to field changes.
We define this function with useEffectEvent, from React 19.2, so that it accesses the latest values. It only receives the current step's fields, so it merges them into values and calls onValuesChange.
Updating the flow
Each Form is rendered inside the flow, so the two extra props have to reach it through params. We also export initialValues, with an initial value for every field, to use as the parent's initial state.
// src/flow.tsx
import type { UnionToIntersection } from "type-fest";
import type { Flow, s } from "@formity/react";
import type { FormStatus } from "./types/status";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Form } from "./components/form";
import * as constants from "./constants";
type Values = UnionToIntersection<Fields[keyof Fields]>;
type Fields = {
contact: {
firstName: string;
lastName: string;
email: string;
};
shipping: {
address: string;
city: string;
postalCode: string;
country: string;
};
delivery: {
deliveryMethod: string;
};
payment: {
cardholderName: string;
cardNumber: string;
expiryDate: string;
};
};
export type Schema = {
render: React.ReactNode;
struct: [
s.Form<Fields["contact"]>,
s.Form<Fields["shipping"]>,
s.Form<Fields["delivery"]>,
s.Form<Fields["payment"]>,
s.Return<Values>,
];
inputs: Record<never, never>;
params: {
status: FormStatus;
values: Values;
onValuesChange: (values: Values) => void;
};
};
export const flow: Flow<Schema> = [
{
form: {
fields: () => ({
firstName: ["", []],
lastName: ["", []],
email: ["", []],
}),
render: ({ fields, params, back, next }) => (
<Form
key="contact"
defaultValues={fields}
resolver={zodResolver(
z.object({
firstName: z.string().nonempty("Please enter your first name"),
lastName: z.string().nonempty("Please enter your last name"),
email: z.email("Please enter a valid email address"),
}),
)}
heading="Contact"
message="We'll send your order confirmation here."
content={[
{
type: "columns",
columns: [
{
type: "input",
name: "firstName",
label: "First name",
placeholder: "Jane",
},
{
type: "input",
name: "lastName",
label: "Last name",
placeholder: "Smith",
},
],
},
{
type: "input",
name: "email",
label: "Email address",
placeholder: "jane@example.com",
inputType: "email",
},
]}
buttons={{ back: null, next: "Continue" }}
back={back}
next={next}
status={params.status}
values={params.values}
onValuesChange={params.onValuesChange}
/>
),
},
},
{
form: {
fields: () => ({
address: ["", []],
city: ["", []],
postalCode: ["", []],
country: ["", []],
}),
render: ({ fields, params, back, next }) => (
<Form
key="shipping"
defaultValues={fields}
resolver={zodResolver(
z.object({
address: z.string().nonempty("Please enter your address"),
city: z.string().nonempty("Please enter your city"),
postalCode: z.string().nonempty("Please enter your postal code"),
country: z.string().nonempty("Please select your country"),
}),
)}
heading="Shipping address"
message="Where should we deliver your order?"
content={[
{
type: "input",
name: "address",
label: "Address",
placeholder: "123 Main St",
},
{
type: "columns",
columns: [
{
type: "input",
name: "city",
label: "City",
placeholder: "New York",
},
{
type: "input",
name: "postalCode",
label: "Postal code",
placeholder: "10001",
},
],
},
{
type: "select",
name: "country",
label: "Country",
placeholder: "Select a country",
options: constants.countries,
},
]}
buttons={{ back: "Back", next: "Continue" }}
back={back}
next={next}
status={params.status}
values={params.values}
onValuesChange={params.onValuesChange}
/>
),
},
},
{
form: {
fields: () => ({
deliveryMethod: ["", []],
}),
render: ({ fields, params, back, next }) => (
<Form
key="delivery"
defaultValues={fields}
resolver={zodResolver(
z.object({
deliveryMethod: z
.string()
.nonempty("Please select a delivery method"),
}),
)}
heading="Delivery method"
message="Choose how fast you'd like your order to arrive."
content={[
{
type: "radio",
name: "deliveryMethod",
options: constants.deliveryMethods.map((m) => ({
value: m.value,
label: m.label,
description: m.description,
priceLabel: m.priceLabel,
})),
},
]}
buttons={{ back: "Back", next: "Continue" }}
back={back}
next={next}
status={params.status}
values={params.values}
onValuesChange={params.onValuesChange}
/>
),
},
},
{
form: {
fields: () => ({
cardholderName: ["", []],
cardNumber: ["", []],
expiryDate: ["", []],
}),
render: ({ fields, params, back, next }) => (
<Form
key="payment"
defaultValues={fields}
resolver={zodResolver(
z.object({
cardholderName: z
.string()
.nonempty("Please enter the cardholder name"),
cardNumber: z.string().nonempty("Please enter your card number"),
expiryDate: z.string().nonempty("Please enter the expiry date"),
}),
)}
heading="Payment"
message="Your payment information is encrypted and secure."
content={[
{
type: "input",
name: "cardholderName",
label: "Cardholder name",
placeholder: "Jane Smith",
},
{
type: "cardNumber",
name: "cardNumber",
label: "Card number",
},
{
type: "expiryDate",
name: "expiryDate",
label: "Expiry date",
},
]}
buttons={{ back: "Back", next: "Place order" }}
back={back}
next={next}
status={params.status}
values={params.values}
onValuesChange={params.onValuesChange}
/>
),
},
},
{
return: (values) => values,
},
];
export const initialValues: Values = {
email: "",
firstName: "",
lastName: "",
address: "",
city: "",
postalCode: "",
country: "",
deliveryMethod: "",
cardholderName: "",
cardNumber: "",
expiryDate: "",
};
Using the state
Finally, we create the state with useState, starting from initialValues. It lives in the component that calls the useFormity hook, which is also the one that renders the summary.
The hook receives values and setValues through params, the second one as onValuesChange. Each Form calls it on every change, which keeps the state up to date.
All that remains is to use the state where we need it. The Summary component receives its values instead of the empty ones, and shows a summary that updates as users type.
// src/app.tsx
import type { OnReturn, ReturnOutput } from "@formity/react";
import type { Status, FormStatus } from "./types/status";
import { useState, useCallback } from "react";
import { useFormity } from "@formity/react";
import { Summary } from "./components/summary";
import { Done } from "./components/done";
import { flow, initialValues, type Schema } from "./flow";
export default function App() {
const [status, setStatus] = useState<Status<ReturnOutput<Schema>>>({
type: "form",
submitting: false,
});
const onReturn = useCallback<OnReturn<Schema>>(async (output) => {
setStatus({ type: "form", submitting: true });
// Show output in the console
console.log(output);
// Simulate a network request
await new Promise((resolve) => setTimeout(resolve, 1000));
setStatus({ type: "done", output });
}, []);
if (status.type === "done") {
return (
<Done
output={status.output}
onStartOver={() => setStatus({ type: "form", submitting: false })}
/>
);
}
return <Form status={status} onReturn={onReturn} />;
}
interface FormProps {
status: FormStatus;
onReturn: OnReturn<Schema>;
}
function Form({ status, onReturn }: FormProps) {
const [values, setValues] = useState(initialValues);
const form = useFormity({
flow,
params: { status, values, onValuesChange: setValues },
onReturn,
});
return (
<div className="flex h-screen w-full overflow-hidden bg-white">
<main className="flex flex-1 items-start justify-center overflow-y-auto px-6 py-12">
<div className="w-full max-w-lg">{form}</div>
</main>
<Summary
values={{
email: values.email,
city: values.city,
country: values.country,
deliveryMethod: values.deliveryMethod,
}}
/>
</div>
);
}