useFormState
A custom React hook for managing form values, validation, and submission logic.
✅ Features
- Fully typed
- Built-in error handling
- Works with any input field
📦 Usage
1const { values, errors, handleChange, handleSubmit } = useFormState({ 2 initialValues: { name: '', email: '' }, 3 validate: (values) => { 4 const errors: any = {} 5 if (!values.email.includes('@')) errors.email = 'Invalid email' 6 return errors 7 }, 8 onSubmit: (values) => console.log(values) 9})
📋 Source Code
This is the full implementation of useFormState
1import { useState } from 'react'
2
3export function useFormState<T>(initialValues: T) {
4 const [values, setValues] = useState(initialValues)
5
6 const handleChange = (field: keyof T) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
7 setValues(prev => ({ ...prev, [field]: e.target.value }))
8 }
9
10 const reset = () => setValues(initialValues)
11
12 return {
13 values,
14 handleChange,
15 reset,
16 }
17}
18