ISSUE DESCRIPTION issue: values data is reset after first render, when shouldUnregister…
- User
ISSUE DESCRIPTION
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.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /react-hook-form, current file: none) bash-$
Assistant
Let me explore the repository structure to understand the codebase.
Assistant
Let me look at the
_resetfunction and howvaluesis used. Let me also look at the key lines around 155-160.Assistant
Now let me understand the issue. The problem is that
valuesdata is reset after first render, whenshouldUnregisteris provided.Let me look at how
valuesis used inuseForm.Assistant
Let me reproduce the issue first. Let me look at the registration logic and how
_formValuesgets populated.Assistant
Let me understand the issue better. Let me look at how
getValuesworks during submit, and how_formValuesgets populated when fields are registered.Let me look at the
registerfunction and theupdateValid/_updateFieldArray.Actually, let me trace through the scenario:
useForm({ values: { firstName: "test", lastName: "test" }, shouldUnregister: true })createFormControl:_defaultValues = { firstName: "test", lastName: "test" },_formValues = {}(because shouldUnregister).- The form renders with inputs registered via
register("firstName")andregister("lastName").
Let me look at the register function.
Assistant
Let me look at the
generateWatchOutputand_getWatchmore closely, and then reproduce the issue.Assistant
Let me look at the existing tests to understand the testing setup and find related tests for
values+shouldUnregister.Assistant
Let me write a reproduction test based on the codesandbox scenario.
Assistant
Parse error. Let me check the babel config issue - probably TypeScript type annotation. Let me look at the jest config.
Assistant
I need to use the jest config. Let me run the test properly:
Assistant
The import path is wrong. Let me fix it.
Assistant
I reproduced the issue. The inputs are empty (no value) and submit fails. Let me see the full output to understand what the inputs show.
Assistant
Let me look at the
setValuefunction:Assistant
Let me add some debug logging to understand the flow better.
Assistant
Let me look at the commit 802b04720 which introduced the
keepFieldsRefbranch, to understand intent.Assistant
Before this commit:
for (const fieldName of _names.mount) { const value = get(values, fieldName, get(_defaultValues, fieldName)); if (!isUndefined(value)) { set(values, fieldName, value); setValue(fieldName, get(values, fieldName)); } } _formValues = cloneObject(values) as TFieldValues;After this commit:
if (keepStateOptions.keepFieldsRef) { for (const fieldName of _names.mount) { setValue(fieldName, get(values, fieldName)); } } else { _fields = {}; } _formValues = _options.shouldUnregister ? keepStateOptions.keepDefaultValues ? (cloneObject(_defaultValues) as TFieldValues) : ({} as TFieldValues) : (cloneObject(values) as TFieldValues);So before this commit,
_formValues = cloneObject(values)regardless of shouldUnregister. So_formValueswould be the actual values{firstName:'test',...}. This worked.After this commit, when
shouldUnregisteris true,_formValues = {}(unlesskeepDefaultValues). This breaks thevalues+shouldUnregistercase.So the original behavior (before this commit) was: when
valuesis provided,_formValues = cloneObject(values). The shouldUnregister logic of_formValues = {}was newly introduced.Now, why was the shouldUnregister logic added? Let me think about the original
_formValuesinit:let _formValues = _options.shouldUnregister ? ({} as TFieldValues) : (cloneObject(_defaultValues) as TFieldValues);So with shouldUnregister,
_formValuesstarts as{}. The idea is that registered fields populate_formValuesfrom_defaultValues(viaupdateValidAndValue). When shouldUnregister is true, unregistered fields are removed from_formValues.In
_reset, with shouldUnregister, the intent is:_formValuesshould only contain registered (mounted) fields. So after reset,_formValuesshould contain values for mounted fields only. Setting_formValues = {}would lose all values - but then mounted fields would repopulate from_defaultValuesvia the ref re-registration on re-render.Hmm, but the test shows the values are lost. Let me think.
Actually, the problem: with
keepFieldsRef: true(which is what thevalueseffect uses), the fields are kept, so no re-registration happens. But_formValuesis reset to{}, and thesetValueloop that was supposed to populate_formValues[name]is overwritten by_formValues = {}.So the fix should be: when
keepFieldsRefis true, thesetValueloop already populates_formValuesfor mounted fields. Setting_formValues = {}after that loses those values.The correct behavior: when shouldUnregister and keepFieldsRef is true,
_formValuesshould retain the values set by the setValue loop (i.e., the mounted field values). When keepFieldsRef is false,_fields = {}and_formValuesreset to{}is fine (or to _defaultValues if keepDefaultValues).Let me reconsider. The original code before the commit always did
_formValues = cloneObject(values). But that had a bug with shouldUnregister where unmounted field values would be retained in_formValues(since cloneObject(values) keeps everything). The new commit tried to fix that by setting_formValues = {}for shouldUnregister, which repopulates from_defaultValueson re-register.But with
keepFieldsRef: true, there's no re-register, so the values are lost.So the fix: when
keepFieldsRefis true AND shouldUnregister, we should NOT reset_formValuesto{}. Instead, we should build_formValuesfrom the mounted field values.Actually, let me think about what the correct
_formValuesshould be after reset with shouldUnregister:- Only mounted fields should have values in
_formValues. - The values come from
values(the new formValues passed to reset).
So ideally,
_formValuesshould be an object containing only the mounted field names mapped to their values fromvalues.The setValue loop already does
set(_formValues, name, value)for each mounted field. So if we DON'T reset_formValues = {}afterwards, the mounted values are retained. But there could be leftover values from previously-mounted-but-now-unmounted fields.Hmm. Let me think about what the cleanest fix is.
Option A: When
keepFieldsRefis true, skip the_formValuesreset (keep what setValue loop set, but also clear old unmounted values).Option B: Build
_formValuesfresh from mounted fields when shouldUnregister.Let me look at how the
_formValuesreset logic should behave. Actually let me look at the original pre-commit behavior more carefully. Before the commit, for shouldUnregister with values,_formValues = cloneObject(values). So ALL values were kept (including unmounted). That's the behavior that "worked" for the issue (the issue says version 7.71.2 worked... wait, no, the issue is reporting a BUG in 7.71.2).Wait, the issue says version 7.71.2 has the bug. Let me check what version introduced this. The commit 802b04720 is dated July 1, 2025. The current version is 7.76.1. So this is a regression introduced by that commit.
Let me check: was the bug present before the commit? Before the commit,
_formValues = cloneObject(values)so values were retained → submit would work. So the commit introduced the regression.Now, the cleanest fix that preserves the shouldUnregister intent (not retaining unmounted field values) while fixing the values+shouldUnregister case:
When
keepFieldsRefis true, we want_formValuesto contain the mounted field values. The setValue loop populates them. So we should set_formValuesto the values for mounted fields only.Actually, let me reconsider the whole
_formValuesassignment. Let me restructure:_formValues = _options.shouldUnregister ? keepStateOptions.keepDefaultValues ? (cloneObject(_defaultValues) as TFieldValues) : ({} as TFieldValues) : (cloneObject(values) as TFieldValues);When
keepFieldsRefis true and shouldUnregister is true, this sets_formValues = {}. But the setValue loop set values for mounted fields. Setting to{}wipes them.But wait - if we set
_formValues = {}BEFORE the setValue loop, then the setValue loop would populate it. But the order is: setValue loop first, THEN_formValues = {}. So we need to either reorder or skip the reset when keepFieldsRef.Hmm, but the setValue loop uses
_setValuewhich readspreviousValue = get(_formValues, name)and uses_formValues. So if we reset_formValues = {}first then loop, the values would be set into the empty object. That works!But there's subtlety:
setFieldValue(called by_setValue) sets_formValues[name]AND the DOM ref value. So if we set_formValues = {}first, then loop setValue, both_formValuesand DOM get populated.So one fix: move the
_formValuesreset to BEFORE the keepFieldsRef loop. But that changes behavior for the keepDirtyValues branch too... no, the keepDirtyValues branch is separate (theif (keepStateOptions.keepDirtyValues)at the top). The keepFieldsRef/else is in theelse(not keepDirtyValues) branch.Wait, let me re-read the structure:
if (!keepStateOptions.keepValues) { if (keepStateOptions.keepDirtyValues) { // ... keepDirtyValues branch ... } else { if (isWeb && isUndefined(formValues)) { // ... form.reset() DOM ... } if (keepStateOptions.keepFieldsRef) { for (const fieldName of _names.mount) { setValue(fieldName, get(values, fieldName)); } } else { _fields = {}; } _formValues = _options.shouldUnregister ? keepStateOptions.keepDefaultValues ? (cloneObject(_defaultValues) as TFieldValues) : ({} as TFieldValues) : (cloneObject(values) as TFieldValues); _subjects.array.next({ values: { ...values } }); _subjects.state.next({ values: { ...values } as TFieldValues }); } // ... _names reset, _state reset ... }So the keepFieldsRef branch and the
_formValuesreset are both in theelse(not keepDirtyValues) branch.The cleanest fix: when
keepFieldsRefis true and shouldUnregister, set_formValues = {}BEFORE the loop so the loop populates it. OR, keep the loop's result.Actually, simplest: move the
_formValuesassignment to before the loop, OR make the loop re-set after.Let me think about which is cleaner and matches the intent. The intent of
_formValues = {}for shouldUnregister is: start with empty form values, then mounted fields populate. So the natural place is BEFORE the setValue loop.But for the
elsebranch (_fields = {}), there's no loop, so_formValuesreset to{}(or_defaultValues) is the final value. Then on re-render, fields re-register and repopulate_formValuesfrom_defaultValuesviaupdateValidAndValue. So that's fine.So the fix: move the
_formValuesassignment to BEFORE thekeepFieldsRefloop. Let me verify this works for all cases:Case 1: shouldUnregister=false, keepFieldsRef=true.
_formValues = cloneObject(values).- Loop: setValue for mounted fields. Since
_formValuesalready has values,setValuewould set the same values (no real change). DOM gets updated. Fine. Same as before? Before,_formValues = cloneObject(values)after loop. Now before loop. setValue sets_formValues[name]to same value. Effectively same result. ✓
Case 2: shouldUnregister=true, keepFieldsRef=true.
_formValues = {}(keepDefaultValues false).- Loop: setValue for mounted fields →
_formValues[name] = values[name], DOM updated. ✓ This fixes the bug!
Case 3: shouldUnregister=true, keepDefaultValues=true, keepFieldsRef=true.
_formValues = cloneObject(_defaultValues).- Loop: setValue for mounted fields with
values[name]._formValuesalready has_defaultValues(which == values if not changed). setValue updates. ✓
Case 4: keepFieldsRef=false (else branch).
_fields = {}._formValues = shouldUnregister ? ... : cloneObject(values).- No loop. Re-render repopulates. Same as before. ✓
So moving the
_formValuesassignment before the loop works.But wait, there's a subtle issue with
setValueandisValueUnchanged. In_setValue,isValueUnchanged = deepEqual(previousValue, cloneValue). If_formValuesis already set tovalues(case 1), thenpreviousValue = values[name],cloneValue = cloneObject(values[name]). If they're deepEqual,!isValueUnchangedis false, soset(_formValues, name, cloneValue)is skipped, butsetFieldValueis still called (which updates DOM). And theisWatchednotification... Let me check the bottom of_setValue.- Only mounted fields should have values in
Assistant
Let me look at the test that was modified by the commit to ensure I don't break it.
Assistant
Let me search for
keepFieldsReftests.Assistant
Now let me look at the exact lines to edit in the
_resetfunction:Assistant
Wait, I notice the closing brace structure. The
_formValues = ...is OUTSIDE theif (keepStateOptions.keepFieldsRef) {...} else {...}but INSIDE theelse(not keepDirtyValues) branch and insideif (!keepStateOptions.keepValues).Let me re-check the indentation. Lines 1664-1674:
if (keepStateOptions.keepFieldsRef) { for (const fieldName of _names.mount) { setValue( fieldName as FieldPath<TFieldValues>, get(values, fieldName), ); } } else { _fields = {}; } } _formValues = _options.shouldUnregisterSo the
if (keepFieldsRef)block is at 8-space indent, inside theelse(not keepDirtyValues) block at 6-space? Let me re-check by viewing wider context.Assistant
Now I understand the bug. The
_formValues = ...assignment (which resets to{}whenshouldUnregisteris true) runs AFTER thekeepFieldsRefloop that populates_formValuesviasetValue. So the loop's work is wiped out.The
keepFieldsRefpath is used by thevalueseffect inuseForm.ts. WhenshouldUnregister: true,_formValuesbecomes{}, losing the values.The fix: the
_formValuesreset must happen BEFORE thekeepFieldsRefloop (so the loop populates the freshly-reset_formValues), while keeping thekeepDirtyValuespath unchanged (it needs to read the old_formValuesfirst).Let me apply the edit:
Assistant
No python. Let me use node.
Assistant
Wait, I removed the shared
_formValuesassignment which was ALSO used by thekeepDirtyValuesbranch. I need to add the assignment back to thekeepDirtyValuesbranch. Let me check the current state.Assistant
I need to add the
_formValuesassignment back into thekeepDirtyValuesbranch (after its loop). Let me do that.Assistant
Both branches now have the
_formValuesassignment in the correct position. Let me run the reproduction test.Assistant
Still failing. Let me check what
onSubmitreceived now.Assistant
The values are now correct:
{firstName:'test', lastName:'test'}! The submit works now. The only test failure is my assertion about the second argument (the event object). Let me fix the test assertion to confirm.Assistant
The fix works. The full test suite (114 suites, 1112 tests) passed. Let me run the most relevant test files explicitly to be thorough, and also test edge cases.
Assistant
All passing. Let me test more edge cases: changing
valuesover time, andvalues+shouldUnregister+keepDirtyValues.Assistant
All edge cases pass. Let me run the complete test suite (including server tests) one final time to ensure no regressions.
Assistant
All 119 test suites pass (1123 tests). Now let me remove the temporary repro test file and verify my change passes prettier.
Assistant
Prettier found issues (likely indentation). Let me run prettier to fix the formatting on my changed section.
Assistant
Prettier also reformatted some unrelated pre-existing style issues. Let me revert the file and re-apply only my intended change cleanly to keep the diff minimal.
Assistant
Let me open the file at the relevant section and use the edit tool for a clean change.
Assistant
Now let me make the edit. First, add the
_formValuesassignment in thekeepDirtyValuesbranch (after the for loop, line 1644-1645):Assistant
Now let me move the
_formValuesassignment in theelsebranch to before thekeepFieldsRefloop (insert before line 1671), and remove the shared assignment at lines 1683-1687.Assistant
The edit went wrong - there's an extra
}and a duplicate_subjects.array.next({. The line numbers shifted. Let me revert and redo carefully.Assistant
Let me use a node script to do the precise full-block replacement in one step.
Assistant
The prettier warning may be from pre-existing unrelated style issues. Let me check by running prettier --write and comparing which lines it touches.
Assistant
Prettier's only formatting changes to my added lines are... actually the diff shows my added lines match exactly what I wrote — prettier did NOT reformat my additions. The 3 prettier changes (lines 1114, 1188, 1525) are pre-existing unrelated style issues. To keep my diff minimal, I'll restore my pre-prettier version (which only contains my change) and leave the unrelated lines untouched.
Assistant
There's a
package.jsonchange too — likely from running npm. Let me check and revert it.Assistant
npm added a dependency to package.json. Let me revert package.json and check for package-lock changes.
Assistant
Let me confirm prettier doesn't flag my added lines specifically by diffing a prettier-formatted copy against my version, restricted to my region.
Assistant
The
npx prettier /tmp/mine.tsused default config (double quotes), not the repo's. The in-repoprettier --checkonly flagged 3 pre-existing issues (lines 1114, 1188, 1525). Let me confirm those pre-existing issues exist in the original HEAD file too.Assistant
Confirmed — the prettier warning pre-exists in HEAD (not caused by my change). My added lines are correctly formatted. Let me view my final diff.
Assistant
The diff is clean and minimal. Let me re-create the repro test, run it plus the full suite to confirm with the final version, then remove the temp test.
Assistant
All edge cases pass. Now let me remove the temp test and run the full suite one final time to confirm no regressions.
Assistant
All 118 suites pass (1120 tests, original count restored). Let me also run the TypeScript type check to make sure the change compiles.
Assistant
TypeScript compiles cleanly. Let me do a final git status check.
Assistant
The fix is complete and minimal. Let me summarize.
Summary
Root cause
The issue: when
valuesis provided touseFormtogether withshouldUnregister: true, the form values were reset to{}after the first render, so submitting the form yielded empty data.In
useForm.ts, thevaluesprop triggerscontrol._reset(props.values, { keepFieldsRef: true, ... })(introduced by commit802b04720). Inside_reset(src/logic/createFormControl.ts), the code was:if (keepStateOptions.keepFieldsRef) { for (const fieldName of _names.mount) { setValue(fieldName, get(values, fieldName)); // populates _formValues[name] } } else { _fields = {}; } _formValues = _options.shouldUnregister ? keepStateOptions.keepDefaultValues ? (cloneObject(_defaultValues) as TFieldValues) : ({} as TFieldValues) // <-- wipes the values just set above : (cloneObject(values) as TFieldValues);When
shouldUnregisteristrue(andkeepDefaultValuesis false),_formValueswas reassigned to{}after thekeepFieldsRefloop had populated it viasetValue. SincekeepFieldsRef: truekeeps the field references (no re-registration/repopulation happens on re-render), the values were permanently lost — hence empty inputs and an empty submit payload.Fix
Moved the
_formValuesreassignment to before thekeepFieldsRefloop in the non-keepDirtyValuesbranch, so the freshly-reset_formValuesis then populated with the mounted field values by thesetValueloop. ThekeepDirtyValuesbranch keeps the assignment after its loop (it must read the old_formValuesto detect dirty fields first). The previously-shared trailing assignment was removed and duplicated into each branch with the correct ordering.Checklist
- Reproduced the error: Yes — wrote a test mirroring the Codesandbox (
useForm({ values, shouldUnregister: true })+ submit) and confirmed it failed with{}received and empty inputs. - Confirmed the fix resolves the error: Yes — after the change, the form submits
{ firstName: 'test', lastName: 'test' }and inputs render the values. - Thought about edge cases: Yes — tested (a) the basic submit case, (b) async/changing
valueswithshouldUnregister, and (c)values+shouldUnregister+resetOptions.keepDirtyValues. All pass. ThekeepDirtyValuespath retains its original behavior (assignment still happens after its loop reads old_formValues); the default-reset path (_fields = {}, re-registration repopulates from_defaultValues) is unchanged. - Ran existing tests: Yes — all 118 test suites / 1120 tests pass (web + server), and
tsc --noEmitis clean. The pre-existing prettier warnings in this file are unrelated to my change (present on HEAD) and left untouched to keep the diff minimal.
- Reproduced the error: Yes — wrote a test mirroring the Codesandbox (
Assistant
The user is telling me no tool call was invoked. I need to submit my changes now since I've completed the fix. Let me run the submit command.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.5-35B-A3BCompare side by side →
Qwen/Qwen3.5-35B-A3BCompare side by side →