Skip to main content

useForm

A hook to manage state of a form. This is an opinionated hook that will manage all internal state of a form and add isValid and errorMessages properties to each field for validation purpose, these properties are derived from the validator function provided to hook and can used to render error messages and to check if the form field is valid.

import { useForm } from 'react-use-custom-hooks';

Usage example

const [formData, setFormData] = useForm(initialState);
  1. The initial state passed to this hook should be an object with key is the field name and value is an object with value and validator properties. The validator function should return isValid and errorMessages for the particular field upon invoking. For example,
useForm({
name: {
value: '',
validator: value => {
return value.length > 0
? {
isValid: true,
errorMessages: [],
}
: {
isValid: false,
errorMessages: ['Name is required'],
};
},
},
});
  1. This hook returns two values: form state and form change handler.
  2. The form state is an object will have the same structure as initialState with isValid and errorMessages properties added to every field.
  3. The form change handler is a function that takes a field name and a new value and updates the form state.
  4. For every call to change handler the validation function will be invoked with new value and form state will be updated accordingly.

Playground

Live Editor
Result
Loading...

API

function useAsync(fn: () => any, options?: Options, deps = []);

Options

PropertyDescriptionTypeDefault
successCallbackCallback function on successFunction-
errorCallbackCallback function on failureFunction-