Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hook Form defaultValues v/s values

When using React Hook Form, while I understand that the "defaultValues" is used to set the form field values on initial form load.

However, let's say there is a dynamic form with dependent fields e.g. if Dropdown Field 1 is set to "ABC", then Field 2 should be set to "ABC 1 Updated" To handle such use cases, is it possible to "watch" Field 1 and based on it's value, update the "defaultValues" with Field 2 then set to "ABC 1 Updated"

or is it not recommended to update "defaultValues" after the initial form load.

I also see "values" in the below documentation, but haven't seen it's usage much. Other option is doing "setValue". Not sure what is the recommended way of handling side effects with a dynamic form with dependent fields.

https://react-hook-form.com/docs/useform#defaultValues

like image 803
copenndthagen Avatar asked Oct 30 '25 14:10

copenndthagen


2 Answers

You should use values if it's dependent on the return of an async function or the field is dynamic. Use defaultValues if the fields are static.

You should never use setValue for updating a field array. This could cause problems in rerendering components. Just put it from values.

values: asynFn ? { ...asyncFn } : defaultValues
like image 139
Pusoy Avatar answered Nov 02 '25 02:11

Pusoy


Yes, it's not recommended to update "defaultValues".

You can use reset or setValue

like image 32
orange Avatar answered Nov 02 '25 02:11

orange



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!