Skip to content
Advertisement

What are major differences between Controlled and Uncontrolled Components in react-hooks-form?

I am using react hooks form. I read from documentation about controlled and uncontrolled.

Controlled

<form onSubmit={handleSubmit(onSubmit)}>
  <input name="firstName" ref={register({ required: true })} />
  <input name="lastName" ref={register} />
  <input type="reset" /> // standard reset button
  <input type="button" onClick={reset} />
  <input type="button" onClick={() => reset({ firstName: "bill" }); }} /> // reset form with values
  <input type="button" onClick={() => {
    reset({
      firstName: "bill"
    }, {
      errors: true, // errors will not be reset 
      dirtyFields: true, // dirtyFields will not be reset
      isDirty: true, // dirty will not be reset
      isSubmitted: false,
      touched: false,
      isValid: false,
      submitCount: false,
    });
  }} />
</form>

and this is UnControlled form

<form onSubmit={handleSubmit(onSubmit)}>
  <Controller 
    as={TextField} 
    name="firstName"
    control={control} 
    rules={ required: true } 
    defaultValue=""
  />
  <Controller 
    as={TextField} 
    name="lastName"
    control={control}
    defaultValue="" 
  />
  
  <input type="submit" />
  <input type="button" onClick={reset} />
  <input
    type="button"
    onClick={() => {
      reset({
        firstName: "bill",
        lastName: "luo"
      });
    }}
  />
</form>

Can somebody please tell what difference does it makes? And what do i gain by making controlled components instead of uncontrolled?

Advertisement

Answer

React Hook Form embraces uncontrolled form and input, which means you can still build controlled form and input as well: https://twitter.com/bluebill1049/status/1286438673546768386

so what’s the difference between ref={register} and Controller?

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement