Skip to main content

Lesson 2 of 9

react-hook-form + Zod - Production Forms

react-hook-form stores field values in refs (not state), so only the invalid fields trigger re-renders - a major performance win for large forms. Zod provides the schema and produces TypeScript-inferred types automatically.

35 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Setup

Setup
# Install
npm install react-hook-form zod @hookform/resolvers

Signup Form with Zod Validation

Signup Form with Zod Validation
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { View, Text, TextInput, Pressable, ScrollView, StyleSheet, KeyboardAvoidingView, Platform } from 'react-native';

// ---- Schema - single source of truth for types AND validation ----
const signupSchema = z.object({
  name: z.string().min(2, 'Name must be at least 2 characters'),
  email: z.string().email('Invalid email address'),
  password: z.string()
    .min(8, 'Password must be at least 8 characters')
    .regex(/[A-Z]/, 'Must contain uppercase letter')
    .regex(/[0-9]/, 'Must contain a number'),
  confirmPassword: z.string(),
}).refine(data => data.password === data.confirmPassword, {
  message: "Passwords don't match",
  path: ['confirmPassword'],
});

// Infer TypeScript type from schema - no duplication
type SignupFormData = z.infer<typeof signupSchema>;

// ---- Reusable Field component ----
interface FieldProps {
  label: string;
  error?: string;
  children: React.ReactNode;
}
function Field({ label, error, children }: FieldProps) {
  return (
    <View style={fieldStyles.wrapper}>
      <Text style={fieldStyles.label}>{label}</Text>
      {children}
      {error ? <Text style={fieldStyles.error} accessibilityRole="alert">{error}</Text> : null}
    </View>
  );
}

// ---- Main Form ----
export function SignupForm({ onSuccess }: { onSuccess: () => void }) {
  const { control, handleSubmit, formState: { errors, isSubmitting } } = useForm<SignupFormData>({
    resolver: zodResolver(signupSchema),
    defaultValues: { name: '', email: '', password: '', confirmPassword: '' },
    mode: 'onBlur', // validate when user leaves field (smoother UX than 'onChange')
  });

  async function onSubmit(data: SignupFormData) {
    await new Promise(r => setTimeout(r, 1000)); // simulate API call
    console.log('Submitting:', data);
    onSuccess();
  }

  return (
    <KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === 'ios' ? 'padding' : 'height'}>
      <ScrollView contentContainerStyle={styles.scroll} keyboardShouldPersistTaps="handled">
        <Text style={styles.heading}>Create Account</Text>

        <Field label="Full Name" error={errors.name?.message}>
          <Controller
            control={control}
            name="name"
            render={({ field: { value, onChange, onBlur, ref } }) => (
              <TextInput
                ref={ref}
                value={value}
                onChangeText={onChange}
                onBlur={onBlur}
                placeholder="Sarah Chen"
                placeholderTextColor="#475569"
                autoCapitalize="words"
                returnKeyType="next"
                style={[styles.input, errors.name && styles.inputError]}
                accessibilityLabel="Full Name"
                accessibilityState={{ invalid: !!errors.name }}
              />
            )}
          />
        </Field>

        <Field label="Email" error={errors.email?.message}>
          <Controller
            control={control}
            name="email"
            render={({ field: { value, onChange, onBlur } }) => (
              <TextInput
                value={value}
                onChangeText={onChange}
                onBlur={onBlur}
                placeholder="sarah@example.com"
                placeholderTextColor="#475569"
                keyboardType="email-address"
                autoCapitalize="none"
                autoCorrect={false}
                style={[styles.input, errors.email && styles.inputError]}
                accessibilityLabel="Email"
              />
            )}
          />
        </Field>

        <Field label="Password" error={errors.password?.message}>
          <Controller
            control={control}
            name="password"
            render={({ field: { value, onChange, onBlur } }) => (
              <TextInput
                value={value}
                onChangeText={onChange}
                onBlur={onBlur}
                placeholder="Min 8 chars, uppercase, number"
                placeholderTextColor="#475569"
                secureTextEntry
                autoCapitalize="none"
                style={[styles.input, errors.password && styles.inputError]}
                accessibilityLabel="Password"
              />
            )}
          />
        </Field>

        <Field label="Confirm Password" error={errors.confirmPassword?.message}>
          <Controller
            control={control}
            name="confirmPassword"
            render={({ field: { value, onChange, onBlur } }) => (
              <TextInput
                value={value}
                onChangeText={onChange}
                onBlur={onBlur}
                placeholder="Re-enter password"
                placeholderTextColor="#475569"
                secureTextEntry
                autoCapitalize="none"
                style={[styles.input, errors.confirmPassword && styles.inputError]}
                accessibilityLabel="Confirm Password"
              />
            )}
          />
        </Field>

        <Pressable
          onPress={handleSubmit(onSubmit)}
          disabled={isSubmitting}
          style={({ pressed }) => [styles.btn, isSubmitting && styles.btnDisabled, pressed && { opacity: 0.8 }]}
          accessibilityRole="button"
          accessibilityLabel={isSubmitting ? 'Submitting registration' : 'Create account'}
          accessibilityState={{ disabled: isSubmitting }}
        >
          <Text style={styles.btnText}>{isSubmitting ? 'Creating...' : 'Create Account'}</Text>
        </Pressable>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  scroll: { padding: 24, paddingBottom: 60 },
  heading: { fontSize: 26, fontWeight: '700', color: '#f1f5f9', marginBottom: 28 },
  input: { backgroundColor: '#1e293b', borderWidth: 1, borderColor: '#334155', borderRadius: 10, padding: 14, fontSize: 15, color: '#f1f5f9', marginTop: 6 },
  inputError: { borderColor: '#f87171' },
  btn: { backgroundColor: '#229c6b', borderRadius: 12, padding: 16, alignItems: 'center', marginTop: 24 },
  btnDisabled: { opacity: 0.6 },
  btnText: { color: 'white', fontSize: 16, fontWeight: '700' },
});
const fieldStyles = StyleSheet.create({
  wrapper: { marginBottom: 16 },
  label: { fontSize: 14, fontWeight: '600', color: '#cbd5e1' },
  error: { fontSize: 12, color: '#f87171', marginTop: 4 },
});

Common Mistakes

  • Using `mode: 'onChange'` on all fields - validates every keystroke, triggers re-renders and is jarring for users. Use `'onBlur'` to validate when user leaves the field, or `'onSubmit'`
  • Forgetting `keyboardShouldPersistTaps='handled'` on the ScrollView - tapping a Pressable inside a ScrollView dismisses the keyboard first, swallowing the tap. This prop makes the first tap go to the button, not dismiss keyboard
  • Not using `Controller` for platform inputs - native pickers, switches, and sliders need `Controller` to connect to react-hook-form's internal refs

Tip

Tip

Practice reacthookform Zod Production Forms in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

High-performance form state management with type-safe schema validation

Practice Task

Note

Practice Task - (1) Write a working example of reacthookform Zod Production Forms 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 reacthookform Zod Production Forms is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.

Key Takeaways

  • react-hook-form stores field values in refs (not state), so only the invalid fields trigger re-renders - a major performance win for large forms.
  • Using `mode: 'onChange'` on all fields - validates every keystroke, triggers re-renders and is jarring for users. Use `'onBlur'` to validate when user leaves the field, or `'onSubmit'`
  • Forgetting `keyboardShouldPersistTaps='handled'` on the ScrollView - tapping a Pressable inside a ScrollView dismisses the keyboard first, swallowing the tap. This prop makes the first tap go to the button, not dismiss keyboard
  • Not using `Controller` for platform inputs - native pickers, switches, and sliders need `Controller` to connect to react-hook-form's internal refs

Topics in This Module

0/9 done