react-hook-form Flashcards
when is control as a prop optional for useWatch hook in react-hook-form
if we are using useFormContext
useWatch
Hook for subscribing to input changes.
watch api causes re-render at the root of the app or form, we should use this, if we are experiencing performance issues.
an example showing usage of FormProvider and useFormContext
https://react-hook-form.com/api/useformcontext
import { useForm, FormProvider, useFormContext } from “react-hook-form”;
export default function App() {
const methods = useForm();
const onSubmit = data => console.log(data);
return (
);
}
function NestedInput() {
const { register } = useFormContext(); // retrieve all hook methods
return ;
}
useFormContext
This custom hook allows you to access the form context. useFormContext is intended to be used in deeply nested structures, where it would become inconvenient to pass the context as a prop
The initial return value from useWatch will always return
what’s inside of defaultValue or defaultValues from useForm.
example of
useWatch execution order matters
if you update a form value before the subscription is in place, then the value updated will be ignored.
setValue(‘test’, ‘data’);
useWatch({ name: ‘test’ }); // ❌ subscription is happened after value update, no update received
useWatch({ name: ‘example’ }); // ✅ input value update will be received and trigger re-render
setValue(‘example’, ‘data’);
control: Object of react-hook-form
Take control of the form
This object contains methods for registering components into React Hook Form.
Important: do not access any of the properties inside this object directly. It’s for internal usage only.
example of control object in react-hook-form
https://react-hook-form.com/api/useform/control
import { useForm, Controller } from “react-hook-form”;
import { TextField } from “@material-ui/core”;
type FormInputs = {
firstName: string
}
function App() {
const { control, handleSubmit } = useForm();
const onSubmit = (data: FormInputs) => console.log(data);
return (
);
}
useController: one-liner
takes control object from the useForm and return properties in field object = {value, ref, …}
used for creating reusable Controlled input component
https://react-hook-form.com/api/usecontroller
it shares the same props and methods as Controller.