Skip to content
forms

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.

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

Bundle size

Build@lunarhue/forms is@lunarhue/forms 0.2.0TanStack Form 1.33.5
Forms + app2.2 kB smaller (11%)17.3 kB19.5 kB
Total2.3 kB smaller (2%)106.9 kB109.1 kB
App only439 B smaller (17%)2.1 kB2.5 kB
@lunarhue/forms 0.2.0
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>
  );
}
TanStack Form 1.33.5
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>
  );
}

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 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.

Last updated