ReactMedium
Performance in forms?
Form performance problems usually come from re-rendering the whole form on every keystroke. Fix them by using uncontrolled inputs (React 19 form Actions or React Hook Form), keeping per-field state inside field components, subscribing only to the values you need, debouncing expensive validation or async checks, and virtualizing very long dynamic forms.
Techniques
- Uncontrolled inputs: values live in the DOM; no re-render per keystroke. React Hook Form is built on this.
- Field-level state: if you must control inputs, put each field's state in its own component so typing re-renders one field, not the form.
- Selective subscriptions:
useWatch({ name: "country" })in RHF instead ofwatch()at the top, which re-renders on every change. - Memoize heavy children: expensive previews or summaries next to the form (or rely on the React Compiler).
- Debounce: async validation such as "is this username taken?" and autosave.
useDeferredValue: for live previews that are slow to render (markdown preview).- Validation timing:
mode: "onBlur"or"onTouched"instead of"onChange"for heavy schemas. - Large dynamic lists:
useFieldArraywith stablefield.idkeys; virtualize hundreds of rows. - Avoid recreating schemas and option arrays inside the component each render.
- Lazy-load rich inputs (date pickers, editors) only when the field is shown.
Measure
Use the React DevTools Profiler while typing to see which components re-render and how long they take.
Code example
tsx
1import { memo, useDeferredValue, useState } from "react";2import { useForm, useWatch, type Control } from "react-hook-form";34type Post = { title: string; body: string };56const Preview = memo(function Preview({ body }: { body: string }) {7 // imagine an expensive markdown render here8 return <article>{body.split("\n").map((l, i) => <p key={i}>{l}</p>)}</article>;9});1011function LivePreview({ control }: { control: Control<Post> }) {12 const body = useWatch({ control, name: "body" }); // only this component re-renders on typing13 const deferred = useDeferredValue(body); // preview never blocks the textarea14 return <Preview body={deferred} />;15}1617export function PostEditor() {18 const { register, control, handleSubmit } = useForm<Post>({ defaultValues: { title: "", body: "" } });19 const [saved, setSaved] = useState(false);2021 return (22 <form onSubmit={handleSubmit(async (data) => { await fetch("/api/posts", { method: "POST", body: JSON.stringify(data) }); setSaved(true); })}>23 <input {...register("title")} placeholder="Title" />24 <textarea {...register("body")} rows={10} /> {/* uncontrolled: no form re-render per key */}25 <LivePreview control={control} />26 <button>Publish</button> {saved && <span>Saved</span>}27 </form>28 );29}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.