Skip to main content

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

ParameterTypeDefaultDescription
defaultValueT | (() => T)The initial state value or a function returning the initial value.
predicatesArray<(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 }].

PropertyTypeDescription
valueTThe current value of the form field.
setValue(value: T | ((prev: T) => T)) => voidUpdates the state and validates the result. Accepts a direct value or an updater function.
errorsstring[]The active validation error messages.
isValidbooleanWhether the current value passes all validation rules.
status"idle" | "valid" | "error"The current validation status of the field.

Validation Status

StatusDescription
"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 errors and isValid are accurate before the first interaction.
  • setValue accepts either a direct value or an updater function (prev) => next.
  • When emptyInputValidation is false and the value is an empty string, errors are cleared instead of being validated.
  • defaultValue may be a value or a lazy initializer function, resolved once on the first render.