useFormErrors
Standalone error bag.
Import
TypeScript
import { useFormErrors } from '@/hooks';API
Signature
useFormErrors(initial?) → error bag
When to use
Use useFormErrors instead of re-implementing the same pattern in multiple components.
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 · useFormErrorsEditor
function Errors() { const { errors, setError, clearErrors } = useFormErrors<{ email: string }>(); return ( <div> <button onClick={() => setError('email', 'Required')}>Set</button> <button onClick={clearErrors}>Clear</button> <p>{errors.email}</p> </div> ); }
Preview
Implementation source
Full library source for useFormErrors — copy into your project when you are not installing a package yet.
hooks/forms/useFormErrors.ts
import { useCallback, useState } from 'react';
import type { FormErrors } from '../types';
/** Standalone form error bag. */
export function useFormErrors<T extends Record<string, unknown>>(
initial: FormErrors<T> = {},
) {
const [errors, setErrors] = useState<FormErrors<T>>(initial);
const setError = useCallback((field: keyof T, message: string) => {
setErrors((prev) => ({ ...prev, [field]: message }));
}, []);
const clearError = useCallback((field: keyof T) => {
setErrors((prev) => {
const next = { ...prev };
delete next[field];
return next;
});
}, []);
const clearErrors = useCallback(() => setErrors({}), []);
const hasErrors = Object.keys(errors).length > 0;
return { errors, setErrors, setError, clearError, clearErrors, hasErrors };
}
Copy-paste example
useFormErrors.example.tsx
'use client';
import { useFormErrors } from '@/hooks';
export function Errors() {
const { errors, setError, clearErrors } = useFormErrors<{ email: string }>();
return (
<div>
<button onClick={() => setError('email', 'Required')}>Set</button>
<button onClick={clearErrors}>Clear</button>
<p>{errors.email}</p>
</div>
);
}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/useFormErrors.tsfor implementation details