subscribe: UseFormSubscribe<TFieldValues extends FieldValues>
Subscribe to formState changes and value updates. You can subscribe to individual fields or the entire form, while avoiding unnecessary re-renders caused by form changes.
Props
| Name | Type | Description | Example |
|---|---|---|---|
| name | undefined | Subscribe to the entire form | subscribe() |
| string[] | Subscribe on multiple fields by name. | subscribe({ name: ['firstName', 'lastName'] }) | |
| formState | Partial<ReadFormState> | Pick which formState to be subscribed. |
|
| callback | Function | The callback function for the subscription. |
|
| exact | boolean | This prop will enable an exact match for input name subscriptions. | subscribe({ name: 'target', exact: true }) |
This function is intended for subscribing to changes only; dispatching state updates or triggering re-renders is not allowed. eg
setValueorresetThis function shares the same functionality as
createFormControl.subscribe, with the key difference being that createFormControl can be initialized outside of a React component.This function is dedicated for subscribe form state without render, use this function for that instead of watch callback function.
Examples:
import { useForm } from "react-hook-form"type FormInputs = {firstName: stringlastName: string}export default function App() {const { register, subscribe } = useForm<FormInputs>()useEffect(() => {// make sure to unsubscribe;const callback = subscribe({formState: {values: true,},callback: ({ values }) => {console.log(values)},})return () => callback()// You can also just return the subscribe// return subscribe();}, [subscribe])return (<form><input {...register("firstName", { required: true })} /><input {...register("lastName", { required: true })} /></form>)}
Thank you for your support
If you find React Hook Form to be useful in your project, please consider to star and support it.