home / skills / amnadtaowsoam / cerebraskills / form-handling

form-handling skill

/02-frontend/form-handling

This skill helps you build type-safe, validated React forms using React Hook Form and Zod for reliable state management and robust validation.

npx playbooks add skill amnadtaowsoam/cerebraskills --skill form-handling

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
5.6 KB
---
name: Form Handling with React Hook Form and Zod
description: Building type-safe, validated forms in React using React Hook Form for state management and Zod for schema validation.
---

# Form Handling with React Hook Form and Zod

## Overview

Form handling is a critical aspect of web applications that collect data from users. React Hook Form and Zod provide a powerful combination for building forms in React: React Hook Form reduces re-renders and improves performance, while Zod provides validation that is runtime-safe and type-safe.

This skill covers using React Hook Form and Zod to create forms with high validation quality, error handling, async validation, dynamic fields, and integration with UI libraries.

## Why This Matters

- **Increases Conversion Rate**: Easy-to-use forms with clear validation increase conversion rates by 20-30%
- **Reduces Form Abandonment**: Real-time validation and clear error messages reduce form abandonment
- **Improves Data Quality**: Good validation prevents incorrect data entry and reduces data cleaning time
- **Reduces Support Cost**: Clear, working error messages reduce confusion and support tickets
- **Improves User Satisfaction**: Forms that work well and respond quickly create good user experience

---

## Core Concepts

### 1. React Hook Form

Efficient form state management:

- **Reduces Re-renders**: Optimized to minimize unnecessary re-renders
- **Performance**: Fast even with large forms
- **Minimal Code**: Less boilerplate than controlled inputs
- **Integration**: Works with all UI libraries (Material UI, MUI, Chakra UI)

### 2. Zod Validation

Type-safe schema validation:

- **Runtime Validation**: Validates data at runtime
- **TypeScript Inference**: Auto-generates TypeScript types from schemas
- **Composable**: Build complex validation from simple schemas
- **Error Messages**: Customizable, localized error messages

### 3. Form Validation Types

Different validation approaches:

- **Client-Side**: Immediate feedback, better UX
- **Server-Side**: Final validation, security critical
- **Async Validation**: API calls for uniqueness checks
- **Field-Level**: Validate individual fields
- **Form-Level**: Validate multiple fields together

### 4. Error Handling

Managing form errors effectively:

- **Display Errors**: Show errors next to fields or at form level
- **Error Messages**: Clear, actionable error text
- **Validation States**: Show validation in progress for async checks
- **Form-Level Errors**: Display form-wide errors at top

## Quick Start

1. **Install Dependencies**: Install React Hook Form and Zod (`npm install react-hook-form zod @hookform/resolvers`)
2. **Define Zod Schema**: Create validation schema with types
3. **Set Up Form**: Initialize React Hook Form with Zod resolver
4. **Create Form Fields**: Build form with controlled inputs
5. **Add Error Display**: Show validation errors appropriately
6. **Handle Submission**: Process form submission with error handling
7. **Test Validation**: Verify all validation rules work correctly
8. **Integrate UI**: Style form to match design system

```typescript
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

const schema = z.object({
  name: z.string().min(2, 'Name must be at least 2 characters'),
  email: z.string().email('Invalid email address'),
  age: z.number().min(18, 'Must be 18 or older'),
});

type FormData = z.infer<typeof schema>;

function MyForm() {
  const { register, handleSubmit, formState: { errors } } = useForm<FormData>({
    resolver: zodResolver(schema),
  });

  const onSubmit = (data: FormData) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register('name')} placeholder="Name" />
      {errors.name && <p>{errors.name.message}</p>}
      
      <input {...register('email')} placeholder="Email" />
      {errors.email && <p>{errors.email.message}</p>}
      
      <button type="submit">Submit</button>
    </form>
  );
}
```

## Production Checklist

- [ ] Zod schema defined with all validation rules
- [ ] TypeScript types inferred from schemas
- [ ] React Hook Form configured with resolver
- [ ] Error messages clear and localized
- [ ] Form fields properly registered
- [ ] Submission handling with error states
- [ ] Async validation implemented where needed
- [ ] Dynamic fields handling working
- [ ] Form accessible (labels, ARIA, keyboard navigation)
- [ ] Loading states during submission
- [ ] Success/error feedback displayed
- [ ] Form performance optimized
- [ ] Cross-browser tested
- [ ] Mobile responsive

## Anti-patterns

1. **No Validation**: Skipping validation leads to bad data and user frustration
2. **Poor Error Messages**: Vague errors don't help users fix issues
3. **Blocking Submission**: Submitting forms without validation causes server errors
4. **Ignoring Accessibility**: Inaccessible forms exclude users with disabilities
5. **Over-Validation**: Too strict validation frustrates users unnecessarily
6. **No Loading State**: Users don't know form is processing
7. **Silent Failures**: Forms fail without any user feedback

## Integration Points

- **React Hook Form**: [https://react-hook-form.com/](https://react-hook-form.com/)
- **Zod**: [https://zod.dev/](https://zod.dev/)
- **UI Libraries**: Material UI, Chakra UI, Mantine for form components
- **Validation**: Async validation patterns for API checks

## Further Reading

- [React Hook Form Documentation](https://react-hook-form.com/)
- [Zod Documentation](https://zod.dev/)
- [Form Validation Best Practices](https://www.smashingmagazine.com/2020/08/the-ultimate-guide-to-form-validation-in-react/)
- [Accessible Forms](https://web.dev/accessible-forms/)

Overview

This skill teaches building type-safe, validated forms in React using React Hook Form for state management and Zod for schema validation. It focuses on performance, clear error handling, and predictable TypeScript types so forms are robust and maintainable. The content includes patterns for async checks, dynamic fields, and UI integration.

How this skill works

You define a Zod schema to describe and validate form shape and types. React Hook Form manages inputs with minimal re-renders and uses a Zod resolver to run validation on submit or on change. Errors are exposed via formState for field-level or form-level display, and async validation hooks allow uniqueness checks or server-side verification.

When to use it

  • Building forms that require strong runtime validation and TypeScript inference
  • Reducing re-renders and improving form performance in large forms
  • Implementing async checks like email or username uniqueness
  • Creating accessible, localized error messages and UX-friendly validation
  • Integrating forms with component libraries (MUI, Chakra, Mantine)

Best practices

  • Define a complete Zod schema and infer types for your form data
  • Use zodResolver with useForm to centralize validation logic
  • Show clear, actionable error messages next to fields and at form level
  • Add loading and validation-in-progress states for async checks
  • Register all fields with React Hook Form and test dynamic field add/remove flows
  • Ensure accessibility: labels, ARIA attributes, and keyboard navigation

Example use cases

  • Signup form with email uniqueness check and password rules using Zod and async validation
  • Multi-step checkout form with per-step Zod schemas and preserved state via React Hook Form
  • Admin panel with dynamic nested fields (arrays/objects) and runtime type safety
  • Profile settings form integrated with Material UI components and localized error messages
  • Contact form with client-side validation and server-side submission error mapping

FAQ

Do I still need server-side validation?

Yes. Client validation improves UX but server-side validation is required for security and data integrity.

How do I handle async validation like checking email uniqueness?

Use field-level async validators or run checks in onSubmit; set validation state while awaiting API responses and map server errors into formState.