Reputation: 113
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?
Upvotes: 4
Views: 9504
Reputation: 19268
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
?
ref={register}
: https://react-hook-form.com/api#register means uncontrolled input will be subscribed to the input change and retrieve its value by react-hook-form.Controller
: https://react-hook-form.com/api#Controller is a wrapper component which isolating controlled component to re-render within its scope and result in less performance impact on your app/form level.Upvotes: 12