Using Subscriptions to Optimize Form Performance
Provide an example of using the useForm subscription model to selectively rerender components based on form state changes, highlighting the improvement in performance for a large form.
import { useForm } from 'react-hook-form';
First, import the useForm hook from react-hook-form which will be used to manage the form state.
function MyForm() {
const { register, handleSubmit, formState: { isDirty, isSubmitting } } = useForm();
Initialize the useForm hook inside your form component. Extract isDirty and isSubmitting from the formState for use in conditionally rendering or enabling components.
const onSubmit = data => console.log(data);
Define an onSubmit function that logs form data to the console. In a real-world scenario, this is where you would usually send data to a server.
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('firstName')} />
<input {...register('lastName')} />
<button type="submit" disabled={!isDirty || isSubmitting}>{isSubmitting ? 'Submitting...' : 'Submit'}</button>
</form>
);
}
Render the form with two input fields and a submit button. The button is disabled if the form hasn't been modified (isDirty is false) or is currently submitting (isSubmitting is true). Use the register function to include inputs in the form's state management.