Uncontrolled mode
use-form uncontrolled mode to improve performance
Docs
Package
Controlled mode
Controlled mode is the default mode of the form. In this mode, the form data is stored in React state and all components are rerendered when form data changes. Controlled mode is not recommended for large forms.
Example of a form with controlled mode:
As you can see in the example above, form.values
update on every change. This
means that every component that uses form.values
will rerender on every change.
Uncontrolled mode
Uncontrolled mode is an alternative mode of the form introduced in 7.8.0 release. It is now the recommended mode for all forms. Uncontrolled mode provides significant performance improvements for large forms.
With uncontrolled mode, the form data is stored in a ref instead of React state
and form.values
are not updated on every change.
Example of a form with uncontrolled mode:
As you can see in the example above, form.values
do not update at all.
form.getValues
form.getValues
function returns current form values. It can be
used anywhere in the component to get the current form values. It can
be used in both controlled and uncontrolled modes.
Although form.values
can be used to get the current form values in controlled mode, it is
recommended to use form.getValues
instead as it always returns the latest
values while form.values
is outdated in uncontrolled mode and before state
update in controlled mode.
form.getValues()
returns a ref value of the current form values. This means that
you cannot pass it to useEffect
dependencies array as it will always be the same
reference.
Instead of observing form values with useEffect
, use onValuesChange
callback
to listen to form values changes:
form.getInputProps
form.getInputProps returns different props for controlled
and uncontrolled modes. In controlled mode, the returned object has value
prop,
while in uncontrolled mode it has defaultValue
prop.
Uncontrolled mode relies on key
returned from form.key()
to update
components when form.setFieldValue
or form.setValues
are called. You should
set key
supplied by form.key()
to the input component to ensure that it has
updated value:
In case you need to have a list of fields,
do not pass key
to the input component directly, instead add a wrapper
element and pass key
to it:
Uncontrolled mode in custom components
If you want to build a custom component that supports uncontrolled form mode,
you must add support for defaultValue
prop. The best way to add support for
defaultValue
is to use use-uncontrolled hook: