Sub topic 15
Choosing between hand-written forms and a form library
This chapter helps you decide when plain React state is enough for a form and when a form library earns its place. It assumes you know useState, controlled and uncontrolled inputs, FormData, onSubmit with preventDefault, and the validation and accessibility patterns from earlier chapters.
What you already have
By now you can build a complete form with no dependencies. Each piece maps to something a library also provides:
| Concern | Hand-written approach | What a library adds |
|---|---|---|
| Field values | One state object and a shared `handleChange` | A registry of fields and their values |
| Validation | A pure `validate(values)` function run on submit | Schema support and per-field rules |
| Errors | An `errors` object in state | Error state keyed by field, with touched tracking |
| Touched fields | A `touched` object you update on blur | Built-in `touched` and `dirty` flags |
| Reset | Set state back to initial values, or change `key` | A `reset()` function with default values |
| Submit | `onSubmit` with `preventDefault` | `isSubmitting`, and a handler that runs only when valid |
| Re-renders | Every keystroke re-renders the form component | Often subscribes fields individually |
A library does not change what a form is. It packages the same state, validation and submit logic so you stop rewriting it.
What hand-written forms cost
Hand-written forms are simple at first and grow in cost as requirements pile up. These are the costs to watch for.
Repeated boilerplate
Each field needs a value, a change path, an error slot, a touched flag and an accessible error element. With three fields this is fine. With thirty it is a lot of code to keep consistent.
Re-renders on every keystroke
A controlled input calls setState on each keystroke, so the component that owns the state re-renders, along with all its children that are not memoized. For a small form this is invisible. For a large form with expensive children, typing can feel sluggish.
You can reduce the cost without a library:
- Keep state close to the inputs that use it, for example in a small field component.
- Wrap expensive siblings in
React.memo. - Use uncontrolled inputs for fields whose value you only need on submit.
Validation timing logic
Showing an error at the right moment is harder than computing it. Common rules are "validate on blur the first time, then on every change", or "do not show errors until the user has touched the field or tried to submit". Each rule adds state and branching.
Async and cross-field rules
Checking whether a username is taken needs a request, a loading state and a way to ignore stale responses. Rules like "end date must be after start date" depend on two fields. Both are doable by hand, and both are where hand-written code tends to get messy.
What form libraries offer
Popular libraries include React Hook Form, Formik and TanStack Form. They differ in design, but they share a set of features.
- Field registration. You tell the library about each field instead of writing state for it.
- Validation integration. Many accept a schema from a validation library such as Zod or Yup, so the same rules can also run on the server.
- Touched, dirty and submitting flags. These come for free.
- Array fields. Adding, removing and reordering repeated groups of inputs, such as a list of phone numbers, is built in.
- Performance model. Some libraries use uncontrolled inputs and refs internally, so typing does not re-render the whole form. React Hook Form works this way. Formik keeps values in React state, so it behaves more like the hand-written approach.
The sketch below shows the same login form using React Hook Form. It needs npm install react-hook-form.
import { useForm } from 'react-hook-form';
export default function LoginForm() {
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm({ defaultValues: { email: '', password: '' } });
async function onSubmit(values) {
console.log('Valid', values);
}
return (
<form onSubmit={handleSubmit(onSubmit)} noValidate>
<label htmlFor="email">Email</label>
<input
id="email"
aria-invalid={Boolean(errors.email)}
aria-describedby={errors.email ? 'email-error' : undefined}
{...register('email', {
required: 'Enter your email address.',
pattern: { value: /@/, message: 'Enter a valid email address.' },
})}
/>
{errors.email && <p id="email-error">{errors.email.message}</p>}
<label htmlFor="password">Password</label>
<input
id="password"
type="password"
aria-invalid={Boolean(errors.password)}
aria-describedby={errors.password ? 'password-error' : undefined}
{...register('password', {
minLength: { value: 8, message: 'Use at least 8 characters.' },
})}
/>
{errors.password && <p id="password-error">{errors.password.message}</p>}
<button type="submit" disabled={isSubmitting}>
Log in
</button>
</form>
);
}Compare it with the hand-written LoginForm from the validation chapter. There is no useState, no handleChange and no manual preventDefault. register returns the props that connect each input to the library, and handleSubmit only calls your function when validation passes. The accessibility work is unchanged. A library does not add aria-describedby for you, so you still write it.
What libraries cost
A library is not free, so weigh these costs against the boilerplate it removes.
- A new API to learn. You must understand its model, including how it handles controlled components, custom inputs and default values.
- A dependency. It adds bundle size, upgrades and a risk that the library's design changes.
- Harder custom inputs. A date picker or rich text editor from another package may expect
valueandonChange. Libraries offer a wrapper for this, such asControllerin React Hook Form, but it is an extra step. - Debugging through an abstraction. When a value is wrong, you look inside library state instead of your own.
- Overkill for small forms. For a single search box, the library can be larger than your own code.
A decision process
Use the following questions in order. Stop at the first one that gives a clear answer.
- Does the form have one to three fields and simple rules? Write it by hand.
- Do you only need the values when the user submits? Consider an uncontrolled form with
FormData. - Do you need to react to values as the user types, such as live formatting, dependent fields or instant validation? Use controlled inputs, by hand or through a library.
- Does the form have many fields, array fields, multi-step flows or async validation? Use a library.
- Do you share validation rules with a server, or across many forms in one app? Use a library with schema support, so the rules live in one place.
- Are you seeing typing lag in a large form? First try moving state down and memoizing. If that fails, use a library that avoids re-rendering on each keystroke.
Common mistakes
- Adopting a library for one input. The code you save is smaller than the dependency you add.
- Mixing both models in one field. Passing
valueto an input that a library registers as uncontrolled produces conflicts and warnings. Let one system own each field. - Assuming the library handles accessibility. Labels,
aria-invalidandaria-describedbyare still your job. - Trusting client validation. Browser-side checks, whether hand-written or from a library, can be bypassed. Always validate again on the server.
- Rewriting a working form. If a hand-written form is stable and its cost is acceptable, moving it to a library is rarely worth the risk.
Summary
Hand-written forms give you full control and no dependencies, and they suit small forms. Libraries remove repeated code and help with array fields, async validation, shared schemas and render performance. Choose based on form size, how you need to use values (on submit or while typing), and measured problems, not habit.
Exercise
You are building a settings page with 25 fields, a repeatable list of email addresses, and validation rules that the server also enforces. Typing in one section feels slow. Which approach do you choose, and why?
Show answer
Use a form library, preferably one with schema validation support. The repeatable email list is an array field, which libraries handle directly. A shared schema keeps client and server rules in one place. A library that registers inputs as uncontrolled, such as React Hook Form, avoids re-rendering the whole form on each keystroke, which addresses the lag. You could first try moving state into smaller components and memoizing slow children, but the other requirements already favor a library.
Exercise
A teammate replaces a three-field login form with a form library, and now a custom password input shows stale text. What is the likely cause, and how do you fix it?
Show answer
The custom input probably expects controlled props (value and onChange), but the library registered it as an uncontrolled field, so the two models conflict. Wrap the input with the library's controlled adapter, such as Controller in React Hook Form, so the library supplies value and onChange. Also question whether a library was needed for a three-field form, since hand-written state would avoid the conflict.