React hook form(4) - useFormContext & useFormState & useWatch


Posted by TempuraEngineer on 2023-04-08

目錄


useFormContext是甚麼

useFormContext可以讓你在一些結構比較深的地方取得form的context,可以把它想成useForm+useContext

可用於多頁共用一個表單的情境


useFormContext用法

  1. 準備表單組件、頁面組件
  2. 在頁面組件引入useForm、FormProvider,並將useForm的回傳值當作props傳給FormProvider

     const formMethods = useForm();
    
     <FormProvider {...formMethods} />
    
  3. 在表單組件引入並呼叫useFormContext,如此就能取得從頁面組件中傳入的方法了

     const {register} = useFormContext();
    
     <TextField
        fullWidth
        label="User Name"
        InputLabelProps={{
           shrink: true
        }}
        {...register("userName")}
     />
    

codesandbox - useFormContext


useFormState是甚麼

useFormState的回傳值和formState一樣都可以取得表單狀態的資訊

但根據官方文件,兩者的差異在使用useFormState可以減少re-render

This custom hook allows you to subscribe to each form state, and isolate the re-render at the custom hook level.
It has its scope in terms of form state subscription, so it would not affect other useFormState and useForm.
Using this hook can reduce the re-render impact on large and complex form application.

useWatch和watch之間的差異也一樣


useFormState和useWatch用法

  1. 設置defaultValues給useForm
    沒有設置defaultValues的話watch或者useWatch無法生效

       const {register} = useForm<Product>({
         defaultValues: {
           product: "apple",
           unitPrice: 20,
           quantity: 10
         }
       });
    
  2. 傳control給hook,如果有用到useFormContext的話則不必

       const {register, control} = useForm<Product>({
         defaultValues: {
           product: "apple",
           unitPrice: 20,
           quantity: 10
         }
       });
    
       const { isDirty } = useFormState({
         control
       });
    
       const [unitPrice, quantity] = useWatch({
         name:['unitPrice', 'quantity']
         control
       });
    
       return (
           // 略
           <p>total: {unitPrice * quantity}</p>
           <Button disabled={!isDirty}></Button>
       );
    

codesandbox - useFormState & useWatch


參考資料

react-hook-form - useFormContext
react-hook-form - useFormState
react-hook-form
Why useFormState vs formState?
react-hook-form - useWatch example


#react-hook-form #useFormState #useWatch







Related Posts

550. Game Play Analysis IV

550. Game Play Analysis IV

【THM Walkthrough】Exploiting Active Directory (2)

【THM Walkthrough】Exploiting Active Directory (2)

使用 VSCODE DEBUG 對 VUE + VITE 專案進行偵錯

使用 VSCODE DEBUG 對 VUE + VITE 專案進行偵錯


Comments