# Profile settings

> A loaded form with a Zod schema, change marks, a clean form after save and a refresh that keeps edits, built with both libraries.

Source: https://forms.lunarhue.dev/react/compared/profile

A settings screen that loads an existing profile from the server, built once with `@lunarhue/forms` and once with [TanStack Form](https://tanstack.com/form). Both render the exact same markup and hit the same mock API; toggle between builds in the preview to see them behave identically.

| Build (gzip) | @lunarhue/forms is | @lunarhue/forms 0.2.0 | TanStack Form 1.33.5 |
| --- | --- | --- | --- |
| Forms + app | 2.2 kB smaller (11%) | 17.3 kB | 19.5 kB |
| Total | 2.3 kB smaller (2%) | 106.9 kB | 109.1 kB |
| App only | 439 B smaller (17%) | 2.1 kB | 2.5 kB |

```tsx title="lunarhue/App.tsx"
import { createForms, useField, useForm, useFormContext, useFormState } from "@lunarhue/forms-react";
import { baselineOnSubmit, dirty, rebase } from "@lunarhue/forms-react/plugins";
import { zod } from "@lunarhue/forms-schema/zod";
import { z } from "zod";
import { editProfileElsewhere, getProfile, type Profile, saveProfile, timezones } from "../../shared/server.ts";
import { Loaded, Page, ServerControls } from "../../shared/ui.tsx";
import { Checkbox, Select, TextArea, TextField } from "./fields.tsx";

const forms = createForms({
  plugins: [zod(), dirty(), rebase()],
  fields: { TextField, TextArea, Select, Checkbox },
});

const ProfileSchema = z.object({
  name: z.string().min(1, "Enter your name."),
  email: z.email("Enter a valid email."),
  bio: z.string().max(160, "Keep it under 160 characters."),
  timezone: z.enum(timezones, "Pick a time zone."),
  notifications: z.object({
    product: z.boolean(),
    security: z.boolean(),
    digest: z.enum(["daily", "weekly", "never"]),
  }),
});

// The form starts from the profile the server sent. After a successful
// save, what was sent becomes the new baseline, so the form is clean again
// except for edits made while the save ran.
const profileForm = forms.define((saved: Profile) => ({
  schema: ProfileSchema,
  defaultValues: saved,
  plugins: [baselineOnSubmit()],
  onSubmit: async (value) => {
    await saveProfile(value);
    return "Saved.";
  },
}));

function SaveBar() {
  const form = useFormContext(forms);
  const { dirty: changed, submitting } = useFormState(form, (state) => ({ dirty: state.dirty, submitting: state.submitting }), shallowEqual);
  // `changes()` lists the leaves that differ from the baseline. It is a
  // read, not a subscription, so it runs whenever the root field changes.
  const count = useField(form.root, () => form.store.changes().length);

  // Fields the user hasn't changed take the server's copy. Changed ones keep
  // their text and stay dirty against the new baseline.
  const refresh = async () => {
    const fresh = await getProfile();
    form.plugins.rebase(form.root, fresh, (leaf) => (Object.is(leaf.value, leaf.baseline) ? "take" : "keep"));
  };

  return (
    <div className="save-bar">
      <span className="count">{count === 0 ? "No unsaved changes" : `${count} unsaved ${count === 1 ? "change" : "changes"}`}</span>
      <button type="button" onClick={() => void refresh()}>
        Refresh
      </button>
      <button type="button" disabled={!changed} onClick={() => form.root.reset()}>
        Discard
      </button>
      <button type="submit" disabled={!changed || submitting}>
        {submitting ? "Saving..." : "Save"}
      </button>
    </div>
  );
}

function shallowEqual(a: { dirty: boolean; submitting: boolean }, b: { dirty: boolean; submitting: boolean }) {
  return a.dirty === b.dirty && a.submitting === b.submitting;
}

function ProfileForm({ saved }: { readonly saved: Profile }) {
  const form = useForm(profileForm, saved);
  return (
    <form.Form>
      {(formProps) => (
        <form {...formProps}>
          <form.TextField name="name" label="Name" />
          <form.TextField name="email" label="Email" />
          <form.TextArea name="bio" label="Bio" />
          <form.Select name="timezone" label="Time zone" options={timezones} />
          <fieldset>
            <legend>Notifications</legend>
            <form.Checkbox name="notifications.product" label="Product news" />
            <form.Checkbox name="notifications.security" label="Security alerts" />
            <form.Select name="notifications.digest" label="Digest" options={["daily", "weekly", "never"]} />
          </fieldset>
          <SaveBar />
          <form.State select={(state) => state.submission}>
            {(submission) => <p role="status">{submission.status === "succeeded" ? submission.result : null}</p>}
          </form.State>
        </form>
      )}
    </form.Form>
  );
}

export function App() {
  return (
    <Page title="Profile settings" lede="Dirty tracking, a clean form after save, a refresh that keeps edits, and a Zod schema.">
      <ServerControls>
        <button type="button" onClick={editProfileElsewhere}>
          Edit on the server
        </button>
      </ServerControls>
      <Loaded load={getProfile}>{(saved) => <ProfileForm saved={saved} />}</Loaded>
    </Page>
  );
}
```

```tsx title="lunarhue/fields.tsx"
import { checkboxProps, type Choice, type FieldApi, type FormError, inputProps, selectProps, textareaProps } from "@lunarhue/forms-react";
import type { dirty } from "@lunarhue/forms-react/plugins";
import { CheckShell, FieldShell } from "../../shared/ui.tsx";

// Each component reads `field.dirty`, so its type names the plugin: it fits
// only forms with dirty().
type DirtyField<V> = FieldApi<V, typeof dirty>;

const messages = (field: { readonly shownErrors: readonly FormError[] }) => field.shownErrors.map((error) => error.message);

export function TextField({ field, label }: { readonly field: DirtyField<string>; readonly label: string }) {
  return (
    <FieldShell id={field.id} errorId={field.errorId} label={label} errors={messages(field)} changed={field.dirty}>
      <input {...inputProps(field)} />
    </FieldShell>
  );
}

export function TextArea({ field, label }: { readonly field: DirtyField<string>; readonly label: string }) {
  return (
    <FieldShell id={field.id} errorId={field.errorId} label={label} errors={messages(field)} changed={field.dirty}>
      <textarea rows={3} {...textareaProps(field)} />
    </FieldShell>
  );
}

// `Choice` stands for the field's own options, so on the time zone field
// `options` takes only the zones the schema lists.
interface SelectProps {
  readonly field: DirtyField<Choice>;
  readonly label: string;
  readonly options: readonly Choice[];
}

export function Select({ field, label, options }: SelectProps) {
  return (
    <FieldShell id={field.id} errorId={field.errorId} label={label} errors={messages(field)} changed={field.dirty}>
      <select {...selectProps(field)}>
        {options.map((option) => (
          <option key={option} value={option}>
            {option}
          </option>
        ))}
      </select>
    </FieldShell>
  );
}

export function Checkbox({ field, label }: { readonly field: DirtyField<boolean>; readonly label: string }) {
  return (
    <CheckShell errorId={field.errorId} errors={messages(field)} changed={field.dirty}>
      <input {...checkboxProps(field)} />
      {label}
    </CheckShell>
  );
}
```

```tsx title="tanstack/App.tsx"
import { formOptions, useStore } from "@tanstack/react-form";
import { useState } from "react";
import { z } from "zod";
import { editProfileElsewhere, getProfile, type Profile, saveProfile, timezones } from "../../shared/server.ts";
import { Loaded, Page, ServerControls } from "../../shared/ui.tsx";
import { useAppForm, withForm } from "./form.tsx";
import { differsAt, rebaseline } from "./rebaseline.ts";

const ProfileSchema = z.object({
  name: z.string().min(1, "Enter your name."),
  email: z.email("Enter a valid email."),
  bio: z.string().max(160, "Keep it under 160 characters."),
  timezone: z.enum(timezones, "Pick a time zone."),
  notifications: z.object({
    product: z.boolean(),
    security: z.boolean(),
    digest: z.enum(["daily", "weekly", "never"]),
  }),
});

// Every field the form renders. The rebaseline helper walks these, since
// TanStack has no list of a form's leaves to hand.
const fieldNames = [
  "name",
  "email",
  "bio",
  "timezone",
  "notifications.product",
  "notifications.security",
  "notifications.digest",
] as const;

const digests = ["daily", "weekly", "never"] as const;

// Shared by the form and by SaveBar, which withForm types from it. The real
// defaults are the loaded profile, passed to useAppForm.
const blankProfile: Profile = {
  name: "",
  email: "",
  bio: "",
  timezone: "Europe/London",
  notifications: { product: false, security: false, digest: "never" },
};

const profileOptions = formOptions({
  defaultValues: blankProfile,
  validators: { onChange: ProfileSchema },
});

const SaveBar = withForm({
  ...profileOptions,
  props: { refresh: async (): Promise<void> => {} },
  render: function Render({ form, refresh }) {
    const count = useStore(form.store, (state) => Object.values(state.fieldMeta).filter((meta) => !meta.isDefaultValue).length);
    const clean = useStore(form.store, (state) => state.isDefaultValue);
    const submitting = useStore(form.store, (state) => state.isSubmitting);

    return (
      <div className="save-bar">
        <span className="count">{count === 0 ? "No unsaved changes" : `${count} unsaved ${count === 1 ? "change" : "changes"}`}</span>
        <button type="button" onClick={() => void refresh()}>
          Refresh
        </button>
        <button type="button" disabled={clean} onClick={() => form.reset()}>
          Discard
        </button>
        <button type="submit" disabled={clean || submitting}>
          {submitting ? "Saving..." : "Save"}
        </button>
      </div>
    );
  },
});

function ProfileForm({ saved }: { readonly saved: Profile }) {
  // `useForm` applies its options again on every render, and an untouched
  // form takes new `defaultValues` as its values. Defaults moved with
  // `form.reset(values)` would snap back to the loaded profile on the next
  // render, so they live in React state and move with each rebaseline.
  const [defaults, setDefaults] = useState(saved);
  const form = useAppForm({
    ...profileOptions,
    defaultValues: defaults,
    onSubmit: async ({ value, formApi }) => {
      await saveProfile(value);
      // What was sent becomes the defaults. A field edited while the save
      // ran keeps the newer text and stays changed.
      rebaseline(formApi, fieldNames, value, (name, current) => differsAt(value, name, current));
      setDefaults(value);
    },
  });

  // Fields the user hasn't changed take the server's copy. Changed ones
  // keep their text and stay changed against the new defaults.
  const refresh = async () => {
    const fresh = await getProfile();
    rebaseline(form, fieldNames, fresh, (name) => form.getFieldMeta(name)?.isDefaultValue === false);
    setDefaults(fresh);
  };

  return (
    <form
      noValidate
      onSubmit={(event) => {
        event.preventDefault();
        void form.handleSubmit();
      }}
    >
      <form.AppField name="name">{(field) => <field.TextField label="Name" />}</form.AppField>
      <form.AppField name="email">{(field) => <field.TextField label="Email" />}</form.AppField>
      <form.AppField name="bio">{(field) => <field.TextArea label="Bio" />}</form.AppField>
      <form.AppField name="timezone">{(field) => <field.Select label="Time zone" options={timezones} />}</form.AppField>
      <fieldset>
        <legend>Notifications</legend>
        <form.AppField name="notifications.product">{(field) => <field.Checkbox label="Product news" />}</form.AppField>
        <form.AppField name="notifications.security">{(field) => <field.Checkbox label="Security alerts" />}</form.AppField>
        <form.AppField name="notifications.digest">{(field) => <field.Select label="Digest" options={digests} />}</form.AppField>
      </fieldset>
      <SaveBar form={form} refresh={refresh} />
      <form.Subscribe selector={(state) => state.isSubmitSuccessful}>
        {(succeeded) => <p role="status">{succeeded ? "Saved." : null}</p>}
      </form.Subscribe>
    </form>
  );
}

export function App() {
  return (
    <Page title="Profile settings" lede="Dirty tracking, a clean form after save, a refresh that keeps edits, and a Zod schema.">
      <ServerControls>
        <button type="button" onClick={editProfileElsewhere}>
          Edit on the server
        </button>
      </ServerControls>
      <Loaded load={getProfile}>{(saved) => <ProfileForm saved={saved} />}</Loaded>
    </Page>
  );
}
```

```tsx title="tanstack/form.tsx"
// The app's form hook and field components. Each component marks itself
// changed while its value differs from the form's default values.
import { createFormHook, createFormHookContexts, useStore } from "@tanstack/react-form";
import { useId } from "react";
import { CheckShell, FieldShell } from "../../shared/ui.tsx";

const { fieldContext, formContext, useFieldContext } = createFormHookContexts();

/**
 * What every field component needs: ids, the errors to show and the changed
 * mark. Errors wait for a blur or a submit, as `isTouched` turns true on the
 * first keystroke. `isDirty` stays true once the user types, so the mark
 * reads `isDefaultValue`, which turns back when the user types the original.
 */
function useFieldView() {
  const field = useFieldContext<unknown>();
  const id = useId();
  const submitted = useStore(field.form.store, (state) => state.submissionAttempts > 0);
  const { isBlurred, errors, isDefaultValue } = field.state.meta;
  const shown = isBlurred || submitted ? errors.map(messageOf) : [];
  return {
    id,
    errorId: `${id}-errors`,
    errors: shown,
    changed: !isDefaultValue,
    aria: {
      "aria-invalid": shown.length > 0 ? true : undefined,
      "aria-describedby": shown.length > 0 ? `${id}-errors` : undefined,
    },
  };
}

/** Schema issues arrive as objects, function validators' errors as strings. */
function messageOf(error: unknown): string {
  if (typeof error === "string") return error;
  if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") return error.message;
  return String(error);
}

function TextField({ label }: { readonly label: string }) {
  const field = useFieldContext<string>();
  const view = useFieldView();
  return (
    <FieldShell id={view.id} errorId={view.errorId} label={label} errors={view.errors} changed={view.changed}>
      <input
        id={view.id}
        name={field.name}
        value={field.state.value}
        onChange={(event) => field.handleChange(event.target.value)}
        onBlur={field.handleBlur}
        {...view.aria}
      />
    </FieldShell>
  );
}

function TextArea({ label }: { readonly label: string }) {
  const field = useFieldContext<string>();
  const view = useFieldView();
  return (
    <FieldShell id={view.id} errorId={view.errorId} label={label} errors={view.errors} changed={view.changed}>
      <textarea
        id={view.id}
        rows={3}
        name={field.name}
        value={field.state.value}
        onChange={(event) => field.handleChange(event.target.value)}
        onBlur={field.handleBlur}
        {...view.aria}
      />
    </FieldShell>
  );
}

/**
 * A select over the field's options. TanStack's field context has no way to
 * tie `options` to the field's value type, so the component takes strings
 * and the caller passes the field's own list.
 */
function Select({ label, options }: { readonly label: string; readonly options: readonly string[] }) {
  const field = useFieldContext<string>();
  const view = useFieldView();
  return (
    <FieldShell id={view.id} errorId={view.errorId} label={label} errors={view.errors} changed={view.changed}>
      <select
        id={view.id}
        name={field.name}
        value={field.state.value}
        onChange={(event) => field.handleChange(event.target.value)}
        onBlur={field.handleBlur}
        {...view.aria}
      >
        {options.map((option) => (
          <option key={option} value={option}>
            {option}
          </option>
        ))}
      </select>
    </FieldShell>
  );
}

function Checkbox({ label }: { readonly label: string }) {
  const field = useFieldContext<boolean>();
  const view = useFieldView();
  return (
    <CheckShell errorId={view.errorId} errors={view.errors} changed={view.changed}>
      <input
        type="checkbox"
        name={field.name}
        checked={field.state.value}
        onChange={(event) => field.handleChange(event.target.checked)}
        onBlur={field.handleBlur}
        {...view.aria}
      />
      {label}
    </CheckShell>
  );
}

export const { useAppForm, withForm } = createFormHook({
  fieldContext,
  formContext,
  fieldComponents: { TextField, TextArea, Select, Checkbox },
  formComponents: {},
});
```

```ts title="tanstack/rebaseline.ts"
import { type AnyFormApi, getBy } from "@tanstack/react-form";

/**
 * Makes `baseline` the form's default values, so fields equal to it read as
 * unchanged. The fields `keep` picks keep their current value and stay
 * changed. TanStack has no call for this: `form.reset(values)` moves the
 * defaults but also writes every value, so the kept ones are written back
 * after it.
 */
export function rebaseline<N extends string>(
  form: AnyFormApi,
  names: readonly N[],
  baseline: unknown,
  keep: (name: N, value: unknown) => boolean,
): void {
  const kept = names.flatMap((name) => {
    const value: unknown = form.getFieldValue(name);
    return keep(name, value) ? [{ name, value }] : [];
  });
  form.reset(baseline);
  for (const { name, value } of kept) form.setFieldValue(name, value);
}

/** True when the value at `name` differs between the two objects. */
export function differsAt(a: unknown, name: string, value: unknown): boolean {
  return !Object.is(getBy(a, name), value);
}
```

## What the form does

The form edits name, email, bio, time zone, and a nested `notifications` object, validated by a shared Zod schema.

Modified fields show a changed indicator that clears if you type the original value back in. The save bar counts modified fields and keeps **Save** disabled while clean. After saving, the form returns to clean except for any field the user edited *while* the save was in flight. Clicking **Discard** reverts to the last saved copy.

Clicking **Edit on the server** simulates a background update; clicking **Refresh** pulls in the server's new values for untouched fields while keeping whatever you edited.

## Where the two implementations differ

On the `@lunarhue/forms` side, we install `zod()`, `dirty()`, and `rebase()` globally and add `baselineOnSubmit()` on the form. The save bar grabs the form via `useFormContext(forms)` inside `<form.Form>`, counts dirty fields with `store.changes()`, and handles Refresh with one `rebase` call.

One nuance to note on our side: `store.changes()` is a plain read rather than a subscription, and the form's `dirty` boolean doesn't flip again on a second edit once the form is already dirty, so the save bar reads the count inside `useField(form.root, ...)` to re-run whenever any value changes.

On the TanStack Form side, the form uses Standard Schema support for Zod, `isDefaultValue`, `form.reset`, `formOptions`, and `withForm`, with a few extra steps to match the same UX:

- `isDirty` stays `true` even after typing the original value back, so change badges and counts read `isDefaultValue` instead.
- Because TanStack has no built-in way to move defaults while keeping selected edits, a small `rebaseline` helper reads kept fields, calls `form.reset(values)`, and writes the kept values back, walking a manually maintained list of field paths.
- `useForm` re-applies options on every render (and an untouched form adopts new `defaultValues`), so defaults moved via `form.reset(values)` would snap back unless tracked in React state. That also means Refresh has to live in the form component and be passed down to the save bar as a prop.
- `withForm` expects `defaultValues` inside `formOptions` even though real values are loaded asynchronously, so shared options carry a blank profile while `useAppForm` overrides it with the loaded data.
- TanStack's field context doesn't constrain `<Select>` options to the field's value type, so `Select` falls back to strings.

## How bundle sizes were measured

[`scripts/size-compare.ts`](https://github.com/LunarHUE/forms/blob/main/scripts/size-compare.ts) builds each app for production with Vite (minified, JavaScript only) in three variants: **Forms + app** (excluding React, `react-dom`, and Zod), **Total** (everything including React and Zod), and **App only** (excluding the form libraries too). Both sides validate with the same Zod schema.

Our packages are measured from their built dist outputs against TanStack Form 1.33.5, verified automatically in CI. Source and shared Playwright specs live in [`examples/compare`](https://github.com/LunarHUE/forms/tree/main/examples/compare).
