← Back to Blog

How To Debug React Hook Form Errors: Use Simple useEffect

Encountering issues with React Hook Form not submitting? This guide walks you through debugging with useEffect, tracking errors, and fixing validation problems

·Matija Žiberna·
CodingReact
How To Debug React Hook Form Errors: Use Simple useEffect

The Problem

Sometimes, when you create a form using React Hook Form, you might encounter an issue where clicking the submit button does nothing. No console logs, no terminal errors—just silence. This can be frustrating, but there's a quick way to debug this issue using two useEffect hooks.

Adding Debug Logs with useEffect

To diagnose the issue, you can use two useEffect hooks to log form value changes and form errors. These logs help identify whether the form is receiving inputs correctly and if there are validation errors preventing submission.

Step 1: Log Form Value Changes

Add this useEffect to monitor form state changes:

useEffect(() => {
  const subscription = form.watch((value) => {
    console.log("Form values changed:", value);
  });

  return () => subscription.unsubscribe();
}, [form]);

Step 2: Log Form Errors

Another common reason why a form might not submit is due to validation errors. To debug this, log the form's errors state:

useEffect(() => {
  console.log("Form errors:", form.formState.errors);
}, [form.formState.errors]);

With these two hooks in place, you can see in the console:

  1. When form values change.
  2. If there are validation errors preventing submission.

Example Log Output

Here's an example of what might appear in the console when form values change:

Form values changed:  {
    "formId": "0U_Kzb-i4n",
    "name": {
        "value": "Matija",
        "hide": false
    },
    "businessName": {
        "value": "Racunalikso svetovanje sp",
        "hide": false
    },
    "services": [
        {
            "id": "6_0tkC",
            "name": {
                "value": "odbinave nomet",
                "hide": false
            },
            "order": {
                "value": 0,
                "hide": false
            },
            "description": {
                "value": "asdas",
                "hide": false
            }
        },
        {
            "id": "Bdie1P",
            "name": {
                "value": "fasada",
                "hide": false
            },
            "order": {
                "value": 1,
                "hide": false
            },
            "description": {
                "value": "sdas",
                "hide": false
            }
        }
    ],
    "serviceArea": [
        {
            "id": "2",
            "description": "Pomurska"
        },
        {
            "id": "3",
            "description": "Podravska"
        },
        {
            "id": "10",
            "description": "Primorsko-notranjska"
        }
    ],
    "email": {
        "value": "ricarod@asd.asd"
    },
    "phone": {
        "value": "1231231as"
    },
    "preferredCommunication": [
        "Messenger"
    ]
}

Example: Debugging a Contact Form

Here's how you can integrate the debugging hooks into a Contact form component using react-hook-form and zod for validation:

import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "../ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import { useEffect } from "react";
import { useFormStep } from "@/lib/hooks/use-form-step";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";

const CommunicationMethodEnum = z.enum(["Messenger", "WhatsApp", "SMS", "Phonecall"]);
const contactSchema = z.object({
  email: z.string().email({ message: "Please enter a valid email address." }),
  phone: z.string().min(5, { message: "Please enter a valid phone number." }),
  preferredCommunication: z.array(CommunicationMethodEnum).min(1, { message: "Please select at least one communication method." })
});

export function Contact({ currentStep }) {
  const form = useForm({
    resolver: zodResolver(contactSchema),
    defaultValues: { email: "", phone: "", preferredCommunication: [] }
  });

  const { handleBack, handleNext } = useFormStep({ currentStep });

  // Debugging hooks
  useEffect(() => {
    const subscription = form.watch((value) => {
      console.log("Form values changed:", value);
    });
    return () => subscription.unsubscribe();
  }, [form]);

  useEffect(() => {
    console.log("Form errors:", form.formState.errors);
  }, [form.formState.errors]);

  const onSubmit = (data) => {
    handleNext(data);
  };

  return (
    <Card className="border-none shadow-none">
      <CardHeader>
        <CardTitle>Contact Information</CardTitle>
        <CardDescription>
          Please provide your contact details for communication.
        </CardDescription>
      </CardHeader>
      <CardContent>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Email Address</FormLabel>
                  <FormControl>
                    <Input placeholder="email@example.com" type="email" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <div className="flex justify-between pt-4">
              <Button type="button" variant="outline" onClick={handleBack}>
                Back
              </Button>
              <Button type="submit">Next</Button>
            </div>
          </form>
        </Form>
      </CardContent>
    </Card>
  );
}

Conclusion

If your React Hook Form is not submitting and not throwing errors, use these two useEffect hooks:

  1. Log form values to check if inputs are updating correctly.
  2. Log form errors to identify any validation issues.

By adding these simple debugging techniques, you can quickly diagnose why your form is not behaving as expected and fix any underlying issues.

14
Enjoyed this article?
Subscribe to my newsletter for more insights and tutorials.