Generated defaultValues are not applied after first render
See original GitHub issueI have a form that includes controlled components (several Material-UI checkboxes). By specifying defaultValues
, I am able to reset the form successfully. However, if defaultValues
changes depending on props, the reset of the controlled components fails.
E.g., this works:
const MyForm = ({ acls }) => {
...
const defaultValues = {
name: '',
acls: [false, false, false, false, false, false, false]
};
const { handleSubmit, register, errors, reset, setValue, control } = useForm({
defaultValues
});
...
}
This does not:
const MyForm = ({ acls }) => {
...
const defaultValues = {
name: '',
acls: Array(acls.length).fill(false)
};
const { handleSubmit, register, errors, reset, setValue, control } = useForm({
defaultValues
});
...
}
I can see that my top-level component gets re-rendered, as acls
changes along the way from 0 to 7 elements. Thus, in the first example, defaultValues
is constant, while in the second it is modified because of the props updating. Is it possible that, somehow, useForm is not being executed upon the second render?
My apologies, I am unsure how to build a codesandbox that replicates this behavior. If you have a hint on how to replicate the props update there, I’d be happy to give it a shot.
Expected behavior
When I recreate a form using useForm
with different parameters, those parameters should take effect.
Desktop (please complete the following information):
- OS: Linux
- Browser: Firefox
- Version: 73
- react-hook-form: 5.6.1
Thank you very much for react-hook-form. I really like what I’m seeing so far!
Issue Analytics
- State:
- Created 3 years ago
- Comments:26 (13 by maintainers)
I’m including the full example here for posterity, in case the code sandbox goes away. The reason I did not use
useFieldArray
is because, in my actual example, I had a more complex form to set up.What is simulated here is a component that generates a dynamic Material-UI form, based on incoming props.
where is the codesandbox to reproduce? if your defaultValues is changing, then you will need to use
reset()
.Reason: we do cache defaultValues inside the hook, otherwise you will have to memo the value yourself which is not great DX.
I have an issue to update FAQ to include this as well.