Lesson 6 of 9
Form State - react-hook-form + Zod
react-hook-form is the industry standard for handling form state in React - it uses uncontrolled inputs by default, resulting in dramatically fewer re-renders than controlled forms. Paired with Zod for schema validation, you get end-to-end type safety from schema to component.
react-hook-form + Zod Integration
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
// 1. Define the schema - single source of truth for types AND validation
const signupSchema = z.object({
email: z.string().email('Must be a valid email'),
password: z
.string()
.min(8, 'At least 8 characters')
.regex(/[A-Z]/, 'Must contain an uppercase letter'),
confirmPassword: z.string(),
role: z.enum(['user', 'admin']),
agreeToTerms: z.boolean().refine(val => val, 'Must accept terms'),
}).refine(data => data.password === data.confirmPassword, {
message: "Passwords don't match",
path: ['confirmPassword'],
});
// 2. TypeScript type inferred from schema - no duplication
type SignupFormData = z.infer<typeof signupSchema>;
// 3. The form component
function SignupForm() {
const {
register,
handleSubmit,
formState: { errors, isSubmitting, isDirty, isValid },
watch,
setError,
reset,
} = useForm<SignupFormData>({
resolver: zodResolver(signupSchema),
mode: 'onBlur', // validate on field blur (not on every keystroke)
defaultValues: {
email: '',
password: '',
confirmPassword: '',
role: 'user',
agreeToTerms: false,
},
});
const password = watch('password'); // watch a specific field value
async function onSubmit(data: SignupFormData) {
try {
await createAccount(data);
reset(); // clear form on success
navigate('/dashboard');
} catch (err) {
// Set server-side errors on specific fields
setError('email', { message: 'This email is already taken' });
}
}
return (
<form onSubmit={handleSubmit(onSubmit)} noValidate>
{/* Email field */}
<div className="field">
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
{...register('email')} // spreads name, ref, onChange, onBlur
aria-invalid={!!errors.email}
aria-describedby="email-error"
/>
{errors.email && (
<span id="email-error" role="alert">{errors.email.message}</span>
)}
</div>
{/* Password */}
<div className="field">
<label htmlFor="password">Password</label>
<input id="password" type="password" {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}
</div>
{/* Role select */}
<div className="field">
<label htmlFor="role">Role</label>
<select id="role" {...register('role')}>
<option value="user">User</option>
<option value="admin">Admin</option>
</select>
</div>
{/* Checkbox */}
<label>
<input type="checkbox" {...register('agreeToTerms')} />
I agree to the Terms & Conditions
</label>
{errors.agreeToTerms && <span role="alert">{errors.agreeToTerms.message}</span>}
<button
type="submit"
disabled={isSubmitting || !isDirty || !isValid}
>
{isSubmitting ? 'Creating account...' : 'Sign Up'}
</button>
</form>
);
}Tip
Tip
Practice Form State reacthookform Zod in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for Form State - react-hook-form + Zod
Practice Task
Note
Practice Task - (1) Write a working example of Form State reacthookform Zod from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Form State reacthookform Zod is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Finished this lesson?