Usage
use-field
hook is a simpler alternative to use-form, it can be used to
manage state of a single input without the need to create a form:
use-field API
use-field
hook accepts the following options object as a single argument:
And returns the following object:
Validate on blur
To validate the field on blur, set validateOnBlur
option to true
:
Validate on change
To validate the field on change, set validateOnChange
option to true
:
Async validation
validate
option accepts both async and sync functions, in both cases the function
must return an error message that will be displayed to the user or null
if the value
is valid. To keep track of async validation state, use isValidating
property:
Async validation can be used with validateOnBlur
option, but not recommended with
validateOnChange
because it will trigger validation on every key press which may
lead to race conditions:
Touched and dirty
To get information about whether the field has been focused at least once, use isTouched
method
and to check if the value has been changed from the initial value, use isDirty
method:
Dirty: not dirty
Touched: not touched
Clear error on change
By default, the error message is cleared when the value changes, to disable this behavior
set clearErrorOnChange
option to false
:
Uncontrolled mode
Uncontrolled mode of use-field
hook works similar to uncontrolled mode of use-form.
In uncontrolled mode, rerenders are minimized and the input value is managed by the input itself.
It is useful if you experience performance issues with controlled mode, but in most cases controlled
mode is recommended as it always provides up to date field information as React state.