issue: values data is reset after first render, when shouldUnregister is provided…
- User
issue:
valuesdata is reset after first render, whenshouldUnregisteris providedVersion Number
7.71.2
Codesandbox/Expo snack
https://codesandbox.io/p/sandbox/blazing-dust-3225h9?file=%2Fsrc%2FApp.js
Steps to reproduce
- Simply submit a form
- See error
Expected behaviour
It is possible to successfully submit a form, when data is provided via
values, andshouldUnregister: trueoption is setWhat browsers are you seeing the problem on?
Chrome
Code of Conduct
- I agree to follow this project's Code of Conduct
Interface
No new interfaces are introduced.
- Assistant
Investigating how
valuesandshouldUnregisterinteract in the codebase to find why data resets after the first render. - Assistant
Implementing the fix:
_resetwithkeepFieldsRefcallssetValuefor mounted fields, then wipes_formValueswhenshouldUnregisteris true. - Assistant
The first fix was too broad — it skipped updating
_formValueswheneverkeepFieldsRefwas set, which broke the non-shouldUnregisterpath. Narrowing the fix. - Assistant
Fixed the bug where
valueswas cleared after the first render whenshouldUnregister: true.Root cause
When
useFormsyncs thevaluesprop, it calls_resetwithkeepFieldsRef: true. In_reset, field values were applied viasetValuefor mounted fields, but then_formValueswas immediately reset to{}becauseshouldUnregisterwas true — wiping whatsetValuehad just written._names.mountwas also cleared, which broke field tracking.Fix
In
createFormControl.ts:- Preserve
_formValuesaftersetValuewhenshouldUnregister+keepFieldsRef— skip the_formValues = {}assignment in that case so mounted field values are kept. - Preserve
_names.mountwhenkeepFieldsRefis true — so field registration isn’t lost during the values sync.
Tests
Added
src/__tests__/useForm/valuesShouldUnregister.test.tsxcovering:- Registered inputs with
values+shouldUnregister - Controlled inputs ()
- Preserve
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.