Why does using useFormContext with formState in a child component cause the parent(useForm) component re-render when validation fails?
#12944
|
Version Number Codesandbox Case A: Triggers component that calls useForm (App component) re-render
Case B: Does NOT trigger component that calls useForm (App component) re-render
I'm wondering:
|
Replies: 1 comment 1 reply
|
Yes, this is expected, and switching to
// src/useForm.ts
_formControl.current.formState = React.useMemo(
() => getProxyFormState(formState, control),
[control, formState],
)
In Case B nobody reads Ways to keep the host quiet: // subscribe only this component, only to this field
const { errors } = useFormState({ name: 'tel' })
// or
const { fieldState } = useController({ name: 'tel' })
// or, for a one-off read in an event handler (no subscription)
const { getFieldState } = useFormContext()Rule of thumb: inside children, use |
Yes, this is expected, and switching to
useFormState/useControlleris the right fix.formStateis a Proxy. Reading a property on it (e.g.errors) is what subscribes to that slice of state. The proxy you get fromuseFormContext()is the same objectuseForm()returned inApp:FormProviderjust passes it down. So whenTelFielddestructuresformState: { errors }from the context, it's not creating a subscription forTelField. It's flipping theerrorsflag on the host's proxy. From then on, every error change re-rendersApp(the component that ownsuseForm)…