useFormState
useFormState is a custom React hook to manage a single form field with validation and error tracking, validating the initial value on mount.
Usage
import { useFormState } from "hookify-react";
export default function ExampleForm() {
const namePredicates = [
(name: string) =>
name.trim().length < 3 ? "Name must be at least 3 characters" : undefined,
(name: string) =>
name.includes("badword") ? "Name contains forbidden words" : undefined,
];
const [name, setName, { errors, isValid, status }] = useFormState(
"",
namePredicates
);
return (
<div style={{ maxWidth: "400px", margin: "auto" }}>
<h2>Sign Up</h2>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
/>
{errors.length > 0 && (
<ul style={{ color: "red" }}>
{errors.map((error, index) => (
<li key={index}>{error}</li>
))}
</ul>
)}
<p>Status: <strong>{status}</strong></p>
<p>Form is {isValid ? "Valid" : "Invalid"}</p>
</div>
);
}
API Reference
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
defaultValue | T | (() => T) | — | The initial state value or a function returning the initial value. |
predicates | Array<(value: T) => string | undefined> | — | Validation functions, each returning an error message or undefined. |
options | { emptyInputValidation?: boolean } | { emptyInputValidation: true } | Optional configuration. When emptyInputValidation is false, an empty string value clears errors. |
Return Value
useFormState returns a tuple [value, setValue, { errors, isValid, status }].
| Property | Type | Description |
|---|---|---|
value | T | The current value of the form field. |
setValue | (value: T | ((prev: T) => T)) => void | Updates the state and validates the result. Accepts a direct value or an updater function. |
errors | string[] | The active validation error messages. |
isValid | boolean | Whether the current value passes all validation rules. |
status | "idle" | "valid" | "error" | The current validation status of the field. |
Validation Status
| Status | Description |
|---|---|
"idle" | The value is unchanged from the initial value and valid. |
"valid" | The value has changed and is valid. |
"error" | The value has validation errors. |
Behavior
- The initial value is validated on mount, so
errorsandisValidare accurate before the first interaction. setValueaccepts either a direct value or an updater function(prev) => next.- When
emptyInputValidationisfalseand the value is an empty string, errors are cleared instead of being validated. defaultValuemay be a value or a lazy initializer function, resolved once on the first render.