subscribe: UseFormSubscribe Since v7.55.0
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 to a single field by name. | subscribe({ name: 'firstName' }) | |
| string[] | Subscribe to multiple fields by name. | subscribe({ name: ['firstName', 'lastName'] }) | |
| formState | Partial<ReadFormState> | Pick which formState to subscribe to. |
|
| callback | Function | The callback function for the subscription. |
|
| exact | boolean = false | Enable exact name matching. When false (default), the subscription fires when the subscribed name is a prefix of the changed field name, or vice versa. Since v7.81.0 When true, it fires when the subscribed field itself or one of its ancestor paths is updated, but not when a nested child path changes (for example, "users.0.name" is updated when "users" is set, while "users" is not updated when "users.0.name" changes). | subscribe({ name: 'target', exact: true }) |
NOTES
This 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 to subscribing to form state without render, use this function for that instead of watch callback function.
Examples:
import { useEffect } from "react"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 starring and supporting it.