useForm
Full form: values, errors, submit.
Import
TypeScript
import { useForm } from '@/hooks';API
Signature
useForm({ initialValues, validate?, onSubmit? }) → form API
When to use
Signup, settings, multi-field forms with validation.
SSR / Next.js
SSR-safe state machines.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useFormEditor
function Signup() { const form = useForm({ initialValues: { email: '', password: '' }, validate: (v) => { const errors: { email?: string; password?: string } = {}; if (!v.email.includes('@')) errors.email = 'Invalid email'; if (v.password.length < 8) errors.password = 'Min 8 chars'; return errors; }, onSubmit: async (values) => { await fetch('/api/signup', { method: 'POST', body: JSON.stringify(values) }); }, }); return ( <form onSubmit={form.handleSubmit}> <input {...form.getFieldProps('email')} placeholder="Email" /> {form.touched.email && form.errors.email} <input type="password" {...form.getFieldProps('password')} /> {form.touched.password && form.errors.password} <button disabled={form.isSubmitting}>Create account</button> </form> ); }
Preview
Implementation source
Full library source for useForm — copy into your project when you are not installing a package yet.
hooks/forms/useForm.ts
import { useCallback, useMemo, useState } from 'react';
import type {
FormState,
FormTouched,
Validator,
} from '../types';
import { useFormValidation } from './useFormValidation';
export interface UseFormOptions<T extends Record<string, unknown>> {
initialValues: T;
validate?: Validator<T>;
onSubmit?: (values: T) => void | Promise<void>;
validateOnChange?: boolean;
validateOnBlur?: boolean;
}
export interface UseFormReturn<T extends Record<string, unknown>>
extends FormState<T> {
handleChange: (
event: React.ChangeEvent<
HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
>,
) => void;
handleBlur: (
event: React.FocusEvent<
HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
>,
) => void;
setFieldValue: <K extends keyof T>(field: K, value: T[K]) => void;
setFieldError: (field: keyof T, message: string) => void;
setFieldTouched: (field: keyof T, touched?: boolean) => void;
setValues: (values: T | ((prev: T) => T)) => void;
handleSubmit: (
event?: React.FormEvent,
) => Promise<void>;
reset: (nextValues?: T) => void;
getFieldProps: (field: keyof T & string) => {
name: string;
value: T[keyof T];
onChange: UseFormReturn<T>['handleChange'];
onBlur: UseFormReturn<T>['handleBlur'];
};
}
/**
* Full form state: values, errors, touched, dirty, submit.
* Supports sync/async validation and async submit.
*/
export function useForm<T extends Record<string, unknown>>(
options: UseFormOptions<T>,
): UseFormReturn<T> {
const {
initialValues,
validate,
onSubmit,
validateOnChange = true,
validateOnBlur = true,
} = options;
const [values, setValues] = useState<T>(initialValues);
const [touched, setTouched] = useState<FormTouched<T>>({});
const [isSubmitting, setIsSubmitting] = useState(false);
const [submitCount, setSubmitCount] = useState(0);
const { errors, setErrors, runValidation, isValid } =
useFormValidation<T>(validate);
const dirty = useMemo(
() => JSON.stringify(values) !== JSON.stringify(initialValues),
[values, initialValues],
);
const setFieldValue = useCallback(
<K extends keyof T>(field: K, value: T[K]) => {
setValues((prev) => {
const next = { ...prev, [field]: value };
if (validateOnChange) void runValidation(next);
return next;
});
},
[validateOnChange, runValidation],
);
const handleChange = useCallback(
(
event: React.ChangeEvent<
HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
>,
) => {
const target = event.target;
const name = target.name as keyof T;
let value: unknown = target.value;
if (target instanceof HTMLInputElement) {
if (target.type === 'checkbox') value = target.checked;
else if (target.type === 'number') {
value = target.value === '' ? '' : target.valueAsNumber;
}
}
setFieldValue(name, value as T[keyof T]);
},
[setFieldValue],
);
const handleBlur = useCallback(
(
event: React.FocusEvent<
HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
>,
) => {
const name = event.target.name as keyof T;
setTouched((prev) => ({ ...prev, [name]: true }));
if (validateOnBlur) void runValidation(values);
},
[validateOnBlur, runValidation, values],
);
const setFieldError = useCallback((field: keyof T, message: string) => {
setErrors((prev) => ({ ...prev, [field]: message }));
}, [setErrors]);
const setFieldTouched = useCallback((field: keyof T, isTouched = true) => {
setTouched((prev) => ({ ...prev, [field]: isTouched }));
}, []);
const reset = useCallback(
(nextValues?: T) => {
setValues(nextValues ?? initialValues);
setTouched({});
setErrors({});
setIsSubmitting(false);
},
[initialValues, setErrors],
);
const handleSubmit = useCallback(
async (event?: React.FormEvent) => {
event?.preventDefault?.();
setSubmitCount((c) => c + 1);
// mark all touched
const allTouched = Object.keys(values).reduce((acc, key) => {
acc[key as keyof T] = true;
return acc;
}, {} as FormTouched<T>);
setTouched(allTouched);
const nextErrors = await runValidation(values);
if (Object.keys(nextErrors).length > 0) return;
if (!onSubmit) return;
setIsSubmitting(true);
try {
await onSubmit(values);
} finally {
setIsSubmitting(false);
}
},
[values, runValidation, onSubmit],
);
const getFieldProps = useCallback(
(field: keyof T & string) => ({
name: field,
value: values[field],
onChange: handleChange,
onBlur: handleBlur,
}),
[values, handleChange, handleBlur],
);
return {
values,
errors,
touched,
dirty,
isSubmitting,
isValid,
submitCount,
handleChange,
handleBlur,
setFieldValue,
setFieldError,
setFieldTouched,
setValues,
handleSubmit,
reset,
getFieldProps,
};
}
Copy-paste example
useForm.example.tsx
'use client';
import { useForm } from '@/hooks';
export function Signup() {
const form = useForm({
initialValues: { email: '', password: '' },
validate: (v) => {
const errors: { email?: string; password?: string } = {};
if (!v.email.includes('@')) errors.email = 'Invalid email';
if (v.password.length < 8) errors.password = 'Min 8 chars';
return errors;
},
onSubmit: async (values) => {
await fetch('/api/signup', { method: 'POST', body: JSON.stringify(values) });
},
});
return (
<form onSubmit={form.handleSubmit}>
<input {...form.getFieldProps('email')} placeholder="Email" />
{form.touched.email && form.errors.email}
<input type="password" {...form.getFieldProps('password')} />
{form.touched.password && form.errors.password}
<button disabled={form.isSubmitting}>Create account</button>
</form>
);
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Field name attributes must match keys in initialValues for handleChange.
- Source of truth: open
hooks/forms/useForm.tsfor implementation details