Skip to content

subscribe

Subscribe to form state update without render

subscribe: UseFromSubscribe<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


NameTypeDescriptionExample
nameundefinedSubscribe to the entire formsubscribe()
stringSubscribe on a specific field value by namesubscribe({ name: 'test' })
string[]Subscribe on multiple fields by name.subscribe(['firstName', 'lastName'])
formStatePartial<ReadFormState>Pick which formState to be subscribed.
subscribe({
formState: {
values: true,
isDirty: true,
dirtyFields: true,
touchedFields: true,
isValid: true,
errors: true,
defaultValues: true,
isSubmitted: true
}
})
callbackFunctionThe callback function for the subscription.
subscribe({
formState: {
values: true
},
callback: ({ values }) => {
console.log(values)
}
})
exactbooleanThis prop will enable an exact match for input name subscriptions.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 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: string
lastName: string
}
export default function App() {
const { register, subscribe } = useForm<FormInputs>()
useEffect(() => {
// make sure to unsubscribe;
const callback = subscribe({
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.