Benefit of using useFormContext vs standard React context #11754
-
Hi everyone, So I'm not asking about the benefits of using form-related context in general. I've used the My question is as to whether there is any benefit of using My current usage requires me to globally access certain functions that would be better suited in the context, so I've had to create a separate export function useFormStuff() {
const form = useFormContext<FormFields>()
const actions = useContext(FormActionContext)
if (!actions)
throw new Error('actions not found')
return { form, actions }
} If I were to create a single context, it would consolidate a lot of code: type FormContext = {
form: ReturnType<typeof useForm<FormFields>>
actions: { someAction: () => void }
}
const FormContext = createContext<FormContext | null>(null)
function MyFormProvider() {
const form = useForm()
const someAction = () => {}
return (
<FormContext.Provider value={{ form, actions: { someAction } }}>
<form>{children}</form>
</FormContext.Provider>
)
}
function useMyForm() {
const context = useContext(FormContext)
if (!context) {
throw new Error('useMyForm must be used within a MyFormProvider')
}
return context
} Are there any drawbacks from using standard react context over the provided |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Another benefit is react-hook-form's |
Beta Was this translation helpful? Give feedback.
FormProvider
receives methods in the hookuseForm
and it never triggers re-render because of the ref-based implementation while normal React's context makes entries childs re-render if you spread<ReactFormProvider {...form}/>
.Another benefit is react-hook-form's
useContext
is type-safe