Hook Examples

Form Tracking

Track form submissions to understand conversion rates, validation errors, and user behavior patterns.

Implementation

tsx
import { track } from "@databuddy/sdk";
import { useCallback } from "react";

export function useFormTracking(formName: string) {
const trackSubmit = useCallback(
  (success: boolean, errors?: Record<string, string[]>) => {
    track("form_submit", {
      form_name: formName,
      success,
      error_count: errors ? Object.keys(errors).length : 0,
      has_errors: !!errors && Object.keys(errors).length > 0,
    });
  },
  [formName]
);

return { trackSubmit };
}

Usage

tsx
function ContactForm() {
const { trackSubmit } = useFormTracking("contact");

const handleSubmit = async (data: FormData) => {
  try {
    await submitForm(data);
    trackSubmit(true);
    toast.success("Message sent!");
  } catch (error) {
    trackSubmit(false, { general: ["Failed to send message"] });
    toast.error("Failed to send message");
  }
};

return <form onSubmit={handleSubmit}>...</form>;
}

What It Tracks

  • Event: form_submit
  • Properties:
    • form_name: Name identifier for the form
    • success: Whether submission was successful
    • error_count: Number of validation errors
    • has_errors: Boolean indicating if errors occurred

Benefits

  • Conversion Analysis: Track form completion rates
  • Error Patterns: Identify common validation issues
  • User Experience: Understand where users struggle with forms

How is this guide?