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
Name | Type | Description | Example |
---|---|---|---|
name | undefined | Subscribe to the entire form | subscribe() |
string | Subscribe on a specific field value by name | subscribe({ name: 'test' }) | |
string[] | Subscribe on multiple fields by name. | subscribe(['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 }) |
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: stringlastName: 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.