Form Management Hook
What you'll build
A useForm hook that manages field values, tracks touched/dirty state, runs validators, and returns props for controlled inputs.
Goals
- Manage form field state in a single object
- Track touched and dirty fields
- Run validators and collect errors
- Generate props for controlled inputs
Prerequisites
- useState and custom hooks
- Controlled inputs in React
- Object spread and computed keys
Steps
- 1
Set up the hook state
Create useForm(initialValues) that holds values, errors, and touched state. Return handleChange, handleBlur, handleSubmit, and the current state.
Codefunction useForm(initialValues) { const [values, setValues] = useState(initialValues); const [errors, setErrors] = useState({}); const [touched, setTouched] = useState({}); return { values, errors, touched }; }Expected result
The hook returns the initial state with empty errors and touched.
- 2
Implement handleChange
handleChange takes an event and updates values[field] using computed property keys. This works for any input with a name attribute.
Codeconst handleChange = (e) => { const { name, value } = e.target; setValues(prev => ({ ...prev, [name]: value })); };Expected result
Typing in a field updates values[fieldName].
- 3
Add validation
Accept a validate function that takes values and returns an errors object. Run it on change or blur, depending on your UX preference.
Hint
Common pattern: validate on blur (when the user leaves a field) and on submit, not on every keystroke.
- 4
Implement handleSubmit
handleSubmit takes an onSubmit callback, prevents default, runs final validation, and only calls onSubmit if there are no errors.
Hint
Mark all fields as touched on submit so all errors show, even for fields the user never visited.
- 5
Build a registration form
Use useForm to build a registration form with name, email, and password. Add a validate function that checks required fields and email format.
Codefunction RegistrationForm() { const { values, errors, handleChange, handleSubmit } = useForm( { name: '', email: '', password: '' }, (vals) => { const errs = {}; if (!vals.name) errs.name = 'Required'; if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(vals.email)) errs.email = 'Invalid email'; if (vals.password.length < 8) errs.password = 'Too short'; return errs; } ); return ( <form onSubmit={handleSubmit(data => console.log('Submitted:', data))}> <input name="name" value={values.name} onChange={handleChange} /> {errors.name && <span>{errors.name}</span>} {/* email, password similarly */} <button type="submit">Register</button> </form> ); }Expected result
Form shows errors on invalid input and logs data on valid submit.
Try it yourself
function useForm(initialValues, validate) {
// TODO: state, handlers, return
}function useForm(v, val) { const [values, setV] = useState(v); const [errors, setE] = useState({}); const handleChange = (e) => setV(p => ({...p, [e.target.name]: e.target.value})); return { values, errors, handleChange }; }What you learned
You built a form management hook — the core of libraries like react-hook-form. Understanding this helps you choose or build the right form solution.
Related Resources
Related Lessons
- React Hooks
Custom hooks encapsulate form logic.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.