Form & File Handling
useFormState
About
React hook for comprehensive form state management with validation and error handling. Manages form values, errors, touched state, and submission.
Installation
Usage
API
Options
| Property | Type | Description |
|---|---|---|
| initialValues | T | Initial form values |
| validate | (name, value, values) => string | undefined | Validation function for fields |
| onSubmit | (values: T) => void | Promise<void> | Callback when form is submitted with valid data |
Return Value
Returns an object with the following properties:
| Property | Type | Description |
|---|---|---|
| values | T | Current form values |
| errors | Partial<Record<keyof T, string>> | Validation errors for each field |
| touched | Partial<Record<keyof T, boolean>> | Touched state for each field |
| isSubmitting | boolean | Whether the form is currently submitting |
| isValid | boolean | Whether the form is valid |
| handleChange | (event) => void | Handle input change events |
| handleSubmit | (event) => void | Handle form submit events |
| setFieldValue | (name, value) => void | Set a specific field value |
| setFieldError | (name, error) => void | Set a specific field error |
| setFieldTouched | (name, touched) => void | Set a specific field as touched |
| reset | () => void | Reset the form to initial values |
Features
- Complete form state - Values, errors, touched state, and submission status
- Field validation - Validate individual fields on change
- Form validation - Validate entire form on submit
- Error tracking - Per-field error messages
- Touched tracking - Know which fields the user has interacted with
- Async submission - Support for async onSubmit handlers
- Programmatic control - Manually set field values, errors, and touched state
- TypeScript support - Full type safety with generics
- Input type support - Handles text, checkbox, textarea, and select inputs
Validation
The validation function receives three parameters:
name- The field name being validatedvalue- The current value of the fieldvalues- All current form values
Return a string for validation errors, or undefined if valid.
Use Cases
- Login/registration forms
- Multi-step forms
- Profile update forms
- Complex forms with cross-field validation
- Forms with async submission
- Forms requiring field-level validation feedback