iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📝

Tackling Form Complexity with Conform

に公開
2025/02/16

Challenges with Forms

Typical contact form

Imagine a simple form like this.
The HTML to achieve this would look like the following.

Example of a simple HTML form
  <div class="form-container">
    <form id="inquiryForm" action="https://example.com/api/inquiry" method="post">
      <div class="form-group">
        <label for="name">Name</label>
        <input type="text" id="name" name="name" autocomplete="name" required>
      </div>
      <div class="form-group">
        <label for="email">Email Address</label>
        <input type="email" id="email" name="email" autocomplete="email" required>
      </div>
      <div class="form-group">
        <label for="message">Inquiry Details</label>
        <textarea id="message" name="message" rows="5" required></textarea>
      </div>
      <div class="button-container">
        <button type="submit" id="submitButton">Send</button>
      </div>
    </form>
  </div>

Since the browser handles the state management, the form implementation is simple.
Dynamic elements are handled by JavaScript, allowing you to focus on the UI implementation.
It would be great if we could implement it this simply, wouldn't it?

Now let's consider the code when implementing this form in React.

Example of form implementation in React
import { useForm } from "react-hook-form";
import { Button, HStack, VStack, Label, Input, Textarea, ErrorMessage } from "@yamada-ui/react";
import { FC } from "react";
import { inquiryFormSchema, type InquiryForm } from "../schema";
import { inquiryAction } from "./actions";
import { valibotResolver } from "@hookform/resolvers/valibot";

export const InquiryForm: FC = () => {
  const {
    register,
    handleSubmit,
    formState: { isSubmitting, errors },
  } = useForm<InquiryForm>({
    resolver: valibotResolver(inquiryFormSchema),
  });

  return (
    <form onSubmit={handleSubmit(inquiryAction)}>
      <VStack>
        <Label>
          Name
          <Input
            {...register("name")}
            type="text"
            autoComplete="name"
            required
            maxLength={255}
          />
        </Label>
        {errors.name && <ErrorMessage>{errors.name.message}</ErrorMessage>}
        <Label>
          Email Address
          <Input
            {...register("email")}
            type="email"
            autoComplete="email"
            required
            maxLength={255}
            pattern="^[^\s@]+@[^\s@]+\.[^\s@]+$"
          />
        </Label>
        {errors.email && <ErrorMessage>{errors.email.message}</ErrorMessage>}
        <Label>
          Inquiry Details
          <Textarea {...register("message")} required/>
        </Label>
        {errors.message && <ErrorMessage>{errors.message.message}</ErrorMessage>}
        <HStack alignSelf="end">
          <Button type="submit" loading={isSubmitting}>
            Send
          </Button>
        </HStack>
      </VStack>
    </form>
  );
};

When implementing forms in React, it is common to use React Hook Form.
By using a form library, you can implement richer validation, step-by-step processing based on values, and retrieve submission states.
It's very convenient because the library handles state management instead of you doing it manually, but as you can see, there's an issue where the JSX tends to become complex.

With Conform, you can cut it down to this!

Example of form implementation with Conform
import { Form, TextareaField, TextField } from "@/ui/form";
import { Button, HStack, VStack } from "@yamada-ui/react";
import { FC, useActionState } from "react";
import { inquiryFormSchema } from "../schema";
import { inquiryAction } from "./actions";

export const InquiryForm: FC = () => {
  const [state, dispatch, isPending] = useActionState(inquiryAction, {
    status: "idle",
  });

  return (
    <Form
      schema={inquiryFormSchema}
      action={dispatch}
      options={{ lastResult: state.submissionResult }}
    >
      {({ field }) => (
        <VStack>
          <TextField name={field.name.name} label="Name" autoComplete="name" />
          <TextField name={field.email.name} label="Email Address" autoComplete="email" />
          <TextareaField name={field.message.name} label="Inquiry Details" />
          <HStack alignSelf="end">
            <button type="submit" loading={isPending}>
              Send
            </button>
          </HStack>
          <FormDebug />
        </VStack>
      )}
    </Form>
  );
};

Just like with HTML, you can now focus solely on the appearance of the form!

Introducing Conform

Conform is a next-generation form library designed with Server Actions in mind.

One of the differences from React Hook Form is the method of registering elements like inputs so the library can recognize them.
As the name suggests, RHF is designed with a heavy dependency on React, directly managing the ref of input elements using the register function.
In contrast, Conform registers the name attribute based on a schema.
Components don't require custom implementations; as long as you can specify a standard name attribute, it will work.

import { useForm, getInputProps } from '@conform-to/react';

function Example() {
  const [form, field] = useForm();

  return (
    <form>
      <input {...getInputProps(field.password, { type: 'password' })} /> {/* Bulk setting with Conform utilities */}
      <input name={field.password.name} /> {/* Setting with Conform's type inference */}
      <input name="password" /> {/* Setting manually */}
    </form>
  )
}

A mechanism similar to the register function, called getXXXProps, is provided for each type of input field, allowing you to set appropriate attributes in bulk.
This includes id, name attributes, validation constraints, and accessibility attributes.
The decisive difference is that validation constraints, which had to be set manually in RHF, can be derived from the schema, and it also supports accessibility.
As a side note, the internal implementation is in Vanilla JS, common in recent libraries, leaving room for future support for libraries other than React.

Simple Form Implementation with Conform and an Implementation Abstraction Layer

From here, I will explain how to achieve the simple implementation introduced at the beginning.

In the React Hook Form example, UI construction, integration of form management, configuration of validation constraints, actions, state management, and error handling were all done within a single component. This is the source of the complexity. While it's necessary to separate these concerns according to the Single Responsibility Principle, it's difficult to achieve this when using React Hook Form. In Conform, since the implementation depends only on the name attribute, it's possible to separate them as follows:

Field Component
import { getInputProps, useField } from "@conform-to/react";
import { Input,InputProps,} from "@yamada-ui/react";
import { ComponentProps, type FC, ReactNode, Ref } from "react";
import { CustomFormControl } from "./form-control";
import { FieldProps } from "./types";
import { getFieldErrorProps } from "./utils";

interface TextFieldProps extends FieldProps<string>, Omit<InputProps, "name"> {}

export const TextField: FC<TextFieldProps> = ({ name = "", label, helperMessage, ...props }) => {
  const [fieldMeta] = useField(name);
  return (
    <CustomFormControl {...{ label, helperMessage }} {...getFieldErrorProps(fieldMeta)}>
      <Input {...props} {...getInputProps(fieldMeta, { type: "text" })} key={fieldMeta.key} />
    </CustomFormControl>
  );
};

You can find the full code here.

Based on the specified name attribute, it handles error messages and value settings all at once. By providing such an abstraction layer, the consumer can set all the attributes that should be configured for that input field simply by specifying the name attribute! Incidentally, within CustomFormControl, common field-related logic is defined, such as linking labels and error messages, displaying icons based on whether a field is required, and adding animations to error messages.

Since useField is a hook that requires FormProvider, let's also abstract that by incorporating it into the Form component.

Form Component
export const Form = <
  TInput extends Record<string, unknown>,
  TOutput extends Record<string, unknown>,
>({
  schema,
  options,
  children,
  ...props
}: FormProps<TInput, TOutput>): JSX.Element => {
  const { form, field } = useCustomForm(schema ?? (v.object({}) as any), options);

  return (
    <FormProvider context={form.context}>
      <form {...props} {...getFormProps(form)}>
        {typeof children === "function" ? children({ form, field }) : children}
      </form>
      <FormStateInput />
    </FormProvider>
  );
};

You can find the full code here.

By preparing a Form component that bundles such common logic, the consumer side no longer needs to call useForm every time; the form can be implemented just by passing the schema where the form definition is described and its default values. Although the form and field contexts can no longer be accessed in the JavaScript part of the component, this is an intentional choice. The form and field contexts in Conform contain values that make the component a target for re-rendering when accessed, and this design prevents accidental access to them at the architectural level. If you want to use them, the aim is to optimize re-rendering by splitting the components and having each access them individually.

While it might be possible to provide such an abstraction layer with React Hook Form with some effort, since RHF depends on Refs, a bit of a trick would be necessary if the user also wants to touch the Ref. And there are some things that only Conform can do.

With Conform, the following code works as is

Prototype implementation of a form without a defined schema
(
  <Form>
    <VStack>
      <TextField label="Name" autoComplete="name" />
      <TextField label="Email Address" autoComplete="email" />
      <TextareaField label="Inquiry Details" />
      <HStack alignSelf="end">
        <Button type="submit">Send</Button>
      </HStack>
    </VStack>
  </Form>
)

This is an implementation using the previously mentioned common Form component, imagining a state where the schema is not yet defined and there are no constraints or validations set. In libraries that require refs, you need to pre-define the code necessary for registering refs, which means you cannot use abstraction layer components during prototyping. This is due to a React constraint where hooks cannot be used within conditional branches. Conform adopts a method that searches for input fields with a name attribute, so you can just leave it as an empty string. Even with such code, it works as is without any type or runtime errors. Being able to create the form UI even before the schema is defined makes trial and error much easier.

Other Benefits of Conform

  • Select component support

Select components in UI libraries have different implementations than HTML select elements, requiring integration with a form library. In Conform as well, you can place such custom-implemented components under its management using the useControl hook.

Example of a Select component
Example of a Select component
import { getSelectProps, useField, useInputControl } from "@conform-to/react";
import { handlerAll, Select, SelectProps } from "@yamada-ui/react";
import { useCallback, type FC } from "react";
import { CustomFormControl } from "./form-control";
import { type FieldProps } from "./types";
import { getFieldErrorProps } from "./utils";

interface SelectFieldProps extends FieldProps<string>, Omit<SelectProps, "name"> {}

export const SelectField: FC<SelectFieldProps> = ({
  name = "",
  label,
  helperMessage,
  onChange,
  ...props
}) => {
  const [fieldMeta] = useField(name);
  const { value, change, blur, focus } = useInputControl(fieldMeta);

  const handleChange = useCallback(handlerAll(change, onChange), [change, onChange]);

  const { defaultValue: _, ...mergedProps } = {
    ...props,
    ...getSelectProps(fieldMeta, { value: false }),
  };
  return (
    <CustomFormControl {...{ label, helperMessage }} {...getFieldErrorProps(fieldMeta)}>
      <Select
        value={value}
        onChange={handleChange}
        onBlur={blur}
        onFocus={focus}
        {...mergedProps}
        key={fieldMeta.key}
      />
    </CustomFormControl>
  );
};

Since custom Select components do not have values that can be retrieved as FormData, they need to be rendered as hidden inputs by Conform. Additionally, if there are differences in events such as blur or focus, you need to customize the timing at which you want to trigger them.

  • Dynamic Input Field Support

Dynamic input fields, which are difficult to implement in other libraries, are automatically inferred from the schema and can be created very easily using field.getFieldList().

  • Of course, it can also be used in SPAs

Many introductory articles for Conform often describe it with the premise of being used with server frameworks like Next.js, but if you perform the FormData transformation—which is usually done on the server—on the client side, it can also be used in SPAs. By parsing the FormData obtained from the event.currentTarget.form of a button's click event without submitting, you can retrieve the values synchronously on the client side. Since it can be implemented more simply than React Hook Form, I use Conform even in SPAs.

Example of usage in an SPA
const handleClick = useCallback<React.MouseEventHandler<HTMLButtonElement>>((event) => {
  const formData = new FormData(event.currentTarget.form);
  const submission = parseWithValibot(formData, { schema: inquiryFormSchema });
  if (submission.status !== "success") return;
  mutate(submission.value); // Send to server via TanStack Query, etc.
}, [mutate]);
  • Reactive state access is also possible

You can access reactive values using form.value or field.{{ name }}.value. It's easy to understand because it can be used simply without any additional APIs. The implementation uses Proxies, so when a value is accessed, it subscribes that component to the value being used.

  • Server-side validation support

Since Conform's validation functions do not depend on React, the same schema and validation functions work on the server side. Therefore, depending on your philosophy, you can choose to perform validation only on the server and not bundle it in the frontend.

  • Progressive Enhancement support

With some ingenuity, it is even possible to create forms that work without JavaScript. While this is an edge case, the fact that it works without JavaScript is evidence of its lightweight nature. I don't think it's something to actively strive for, but it's nice that it can handle such requirements if they arise.

Summary

Conform is a new option for tackling the complexity of forms. Compared to React Hook Form, the implementation is simpler, allowing you to focus on building the UI.

The implementation introduced this time can be verified as working on this site. The source code is also public, so please use it as a reference for your design.
*Note: I copied the form code from another personal project, so there is a "bug" where it actually functions (lol). Please be careful, as any personal information entered will be sent to me.

https://exp.bmth.dev/

GitHubで編集を提案

Discussion