fix(form-core): establish Field-over-Form prioritization for isDefaultValue and resets #2006
main fromrefs/pull/2006/head·merged by crutchcorn(GitHub profile, opens in a new tab) 🎯 Changes#
Fixes : #1973
This PR is built on the fundamental premise that "The most specific scope (Field) must always take precedence over the generic scope (Form)." Similar to variable shadowing in programming or specificity in CSS, an explicit declaration at the field level represents a stronger developer intent than a global default.
Currently, the lack of a clear hierarchy leads to architectural inconsistencies:
- The Paradox:
isDefaultValuemight claim a value is "default," yetreset()restores a completely different value from the form-level config. - The False Positive: Clearing a field to
undefinedincorrectly triggersisDefaultValue: trueeven when explicit defaults are defined at the form level.
By unifying isDefaultValue, form.reset(), and form.resetField() under a single Prioritization Strategy (Field over Form), this PR ensures that TanStack Form behaves as a predictable, high-integrity state machine.
Introduction of Prioritized Default System#
This PR introduces a unified prioritization strategy where Field-level defaults always override Form-level defaults.
Key Changes:#
isDefaultValueDetermination: Now uses a single prioritized default value (Field ?? Form) for comparison instead of a logical OR.form.reset()Consistency: Now merges form-level defaults with currently mounted field-level defaults, preventing the "reset betrayal" where values would unexpectedly change to form-defaults.form.resetField()Consistency: Updated to respect the same priority when resetting individual fields.
Fixed Scenarios:#
- Scenario 1: When a default value is specified, setting the field to
undefinednow correctly setsisDefaultValue: false. - Scenario 2: When form-level and field-level defaults differ, both
isDefaultValueandreset()now consistently follow the field-level default.
⚠️ I Updated Existing Tests#
I’d like to verify if this matches what the maintainers had in mind.
Modified current test cases in FieldApi.spec.ts that were previously based on the incorrect logical OR assumption. These tests were updated to reflect the new prioritized logic, ensuring that isDefaultValue only returns true for the actual value that form.reset() would restore.
isDefaultValue Check Logic AS-IS / TO-BE#
| AS-IS | TO-BE |
|---|---|
resset() Logic AS-IS / TO-BE#
| AS-IS | TO-BE |
|---|---|
#
IMO#
I realize this shifts the precedence closer to a 'Variable Shadowing' model. If this is too big of a breaking change, I'm happy to discuss putting this behind a flag or finding a middle ground. My main goal is to ensure reset() and isDefaultValue rely on the same logic. I believe this prioritization makes the library significantly more predictable. By aligning the internal logic with how developers naturally think about scope and specificity,
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested this code locally with
pnpm test:pr. (Verifiedform-coretests and custom regression tests)
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
Summary by CodeRabbit#
New Features
- Introduced Prioritized Default System that enforces consistent field-level default handling throughout form operations. Field-specific defaults now take precedence over form-wide defaults when resetting forms and deriving field state.
Bug Fixes
- Fixed improper default value detection when explicit values are specified, improving accuracy and reliability of default state tracking.
- 1
View your CI Pipeline Execution ↗ for commit 51d50191277dd4a5be241afbe2f3327573165a55
Command Status Duration Result nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded 1m 23s View ↗ nx run-many --target=build --exclude=examples/**✅ Succeeded 38s View ↗
☁️ Nx Cloud last updated this comment at
2026-05-10 19:27:46UTCMore templates
- @tanstack/form-example-angular-array
- @tanstack/form-example-angular-large-form
- @tanstack/form-example-angular-simple
- @tanstack/form-example-angular-standard-schema
- @tanstack/form-example-lit-array
- @tanstack/form-example-lit-large-form
- @tanstack/form-example-lit-simple
- @tanstack/form-example-lit-standard-schema
- @tanstack/form-example-lit-ui-libraries
- @tanstack/form-example-preact-simple
- @tanstack/form-example-solid-array
- @tanstack/form-example-solid-devtools
- @tanstack/form-example-solid-large-form
- @tanstack/form-example-solid-simple
- @tanstack/form-example-solid-standard-schema
- @tanstack/form-example-react-array
- @tanstack/form-example-react-compiler
- @tanstack/form-example-react-composition
- @tanstack/form-example-react-devtools
- @tanstack/form-example-react-dynamic
- @tanstack/form-example-react-expo
- @tanstack/field-errors-from-form-validators
- @tanstack/form-example-react-large-form
- @tanstack/form-example-react-next-server-actions
- @tanstack/form-example-react-next-server-actions-zod
- @tanstack/form-example-react-query-integration
- @tanstack/form-example-remix
- @tanstack/form-example-react-simple
- @tanstack/form-example-react-standard-schema
- @tanstack/form-example-react-tanstack-start
- @tanstack/form-example-react-ui-libraries
- @tanstack/form-example-svelte-array
- @tanstack/form-example-svelte-large-form
- @tanstack/form-example-svelte-simple
- @tanstack/form-example-svelte-standard-schema
- @tanstack/form-example-vue-array
- @tanstack/form-example-vue-simple
- @tanstack/form-example-vue-standard-schema
@tanstack/angular-form
npm i https://pkg.pr.new/@tanstack/angular-form@2006@tanstack/form-core
npm i https://pkg.pr.new/@tanstack/form-core@2006@tanstack/form-devtools
npm i https://pkg.pr.new/@tanstack/form-devtools@2006@tanstack/lit-form
npm i https://pkg.pr.new/@tanstack/lit-form@2006@tanstack/preact-form
npm i https://pkg.pr.new/@tanstack/preact-form@2006@tanstack/react-form
npm i https://pkg.pr.new/@tanstack/react-form@2006@tanstack/react-form-devtools
npm i https://pkg.pr.new/@tanstack/react-form-devtools@2006@tanstack/react-form-nextjs
npm i https://pkg.pr.new/@tanstack/react-form-nextjs@2006@tanstack/react-form-remix
npm i https://pkg.pr.new/@tanstack/react-form-remix@2006@tanstack/react-form-start
npm i https://pkg.pr.new/@tanstack/react-form-start@2006@tanstack/solid-form
npm i https://pkg.pr.new/@tanstack/solid-form@2006@tanstack/solid-form-devtools
npm i https://pkg.pr.new/@tanstack/solid-form-devtools@2006@tanstack/svelte-form
npm i https://pkg.pr.new/@tanstack/svelte-form@2006@tanstack/vue-form
npm i https://pkg.pr.new/@tanstack/vue-form@2006commit:
51d5019Codecov Report#
:x: Patch coverage is
94.73684%with1 linein your changes missing coverage. Please review. :white_check_mark: Project coverage is 90.76%. Comparing base (6892ed0) to head (51d5019). :warning: Report is 197 commits behind head on main.Files with missing lines Patch % Lines packages/form-core/src/FormApi.ts 94.73% 1 Missing :warning: Additional details and impacted files
@@ Coverage Diff @@ ## main #2006 +/- ## ========================================== + Coverage 90.35% 90.76% +0.41% ========================================== Files 38 59 +21 Lines 1752 2209 +457 Branches 444 555 +111 ========================================== + Hits 1583 2005 +422 - Misses 149 183 +34 - Partials 20 21 +1:umbrella: View full report in Codecov by Sentry. :loudspeaker: Have feedback on the report? Share it here.
:rocket: New features to boost your workflow:
- :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
- :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
Looks clean! I'll need to do some additional checks though, since this is potentially a breaking change instead of a fix.
It may take a few days. Thanks for tackling the issue!
packages/form-core/src/FormApi.ts lines 2561 to 2562OutdatedResolvedby kyu-rong(GitHub profile, opens in a new tab)@@ -2542,3 +2557,6 @@25422557 */25432558 resetField = <TField extends DeepKeys<TFormData>>(field: TField) => {25442559 this.baseStore.setState((prev) => {2560+ const fieldDefault =2561+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition2562+ this.getFieldInfo(field)?.instance?.options.defaultValueThis lint error seems odd. Which part does it think does not need an optional chain?
From a surface level, this looks like a wrong type that should be adjusted to reflect (potential) runtime values.
You're right!
getFieldInfo()always returns a value due to||=initialization, so the first?.is indeed unnecessary.I'll update it to: (without lint disable)
this.getFieldInfo(field).instance?.options.defaultValue@@ -120,4 +120,4 @@120120 expect(field.getMeta().isDefaultValue).toBe(false)121121122122 field.setValue('test')123- expect(field.getMeta().isDefaultValue).toBe(true)123+ expect(field.getMeta().isDefaultValue).toBe(false)Reminder to self: Check git blame.
I don't this change is good, but I want to know the context of why it was explicitly listed as unit test.
@LeCarbonator Thanks for taking the time to review this!
I checked the git blame - this test was intentionally written this way in PR #1456 It wasn't a mistake, so I want to be careful here.
But I think there's a philosophical question: What should "default" mean when form-level and field-level disagree?
The Two Interpretations#
Original (OR logic): "Both are defaults"
isDefaultValue = matches(formDefault) || matches(fieldDefault)Proposed (?? logic): "The one
reset()uses is THE default"isDefaultValue = matches(fieldDefault ?? formDefault)Why I Lean Toward the Proposed Logic#
In #1081, explained the purpose of
isDefaultValue:"if you do something like
!meta.isDefaultValuewill give you the react ecosystem's isDirty"RHF's
isDirtyistruewhencurrentValue !== defaultValue. A form has exactly one clean state.With the original OR logic:
isDefaultValueistruefor both'test'and'another-test'- So
!isDefaultValueisfalsefor both values - This means the form has two clean states
That feels inconsistent with RHF's model. A form should have one default state, not two.
The Practical Problem#
// User checks before reset if (!field.getMeta().isDefaultValue) { form.reset() // "I'm not at default, let me reset" }With OR logic, if value is
'test'(form-level default):isDefaultValue→true→ user skips reset- But
reset()would actually change the value to'another-test'
The user gets misleading information.
I Could Be Wrong#
I understand the original design might have had reasons I'm not aware of. Maybe there are use cases where treating both as "default" makes sense. What's your take on this?
📝 Walkthrough
Walkthrough#
This PR implements a prioritized default-value system for TanStack Form, enforcing field-level defaults over form-level defaults across
isDefaultValuederivation,form.reset(), andform.resetField()operations, with corrected handling to preventundefinedfrom being incorrectly treated as a default value.Changes#
Prioritized Default System
Layer / File(s) Summary Feature Declaration
.changeset/gentle-jars-share.mdAnnounces minor version bump and documents the new prioritized default-value system for isDefaultValue,form.reset(), andform.resetField().Default Value Derivation
packages/form-core/src/FormApi.tsRefines fieldMeta.isDefaultValuecomputation to use a single prioritized default source (field instancedefaultValuefallback to formdefaultValues) viaevaluatehelper.Reset and ResetField Implementation
packages/form-core/src/FormApi.tsUpdates reset()to computenextValuesfrom each field instance'sdefaultValue(when defined), falling back to form defaults; updatesresetField()to apply a prioritizedtargetValueand conditionally write only when notundefined.Test Coverage
packages/form-core/tests/FieldApi.spec.ts,packages/form-core/tests/FormApi.spec.tsCorrects existing isDefaultValueassertion; adds tests for falsy primitive defaults,undefinedhandling, andform.reset()behavior with field-level default prioritization.Estimated code review effort#
🎯 2 (Simple) | ⏱️ ~12 minutes
Poem#
🐰 A form finds clarity at last, Fields now guard their defaults so fast, No more form rules muddying the way, Each field's choice wins the day! Reset prioritizes with care, Default harmony everywhere. ✨
🚥 Pre-merge checks | ✅ 5
✏️ Tip: You can configure your own custom pre-merge checks in the settings.✅ Passed checks (5 passed)
Check name Status Explanation Title check ✅ Passed The title clearly and specifically describes the main change: establishing Field-over-Form prioritization for isDefaultValue and resets, which directly matches the primary objective of the changeset. Description check ✅ Passed The description comprehensively covers the changes, motivation, and impact. It includes completed checklist items, a generated changeset, detailed explanation of the prioritization strategy, test updates, and visual flowcharts showing the before/after logic. Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request. Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request. ✨ Finishing Touches
🧪 Generate unit tests (beta)
- Create PR with unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment `@coderabbitai help` to get the list of available commands and usage tips.Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In @.changeset/gentle-jars-share.md: - Around line 2-5: The changeset claims a minor bump but introduces behavioral precedence altering user-visible semantics (Prioritized Default System) affecting isDefaultValue, form.reset(), and form.resetField(); re-evaluate and change the changeset to a major version bump or gate the behavior behind a feature flag/opt-in, update the .changeset text to reflect the decision, and ensure release notes explicitly document the behavioral change and migration guidance for consumers relying on previous dual-default behavior. In `@packages/form-core/src/FormApi.ts`: - Around line 1135-1140: The code uses nullish coalescing (??) so an explicit field default of null is treated as missing and falls back to form defaults; update the logic in the evaluate call to treat only undefined as "missing" (preserve null/false/0 as valid defaults). Concretely, retrieve the field-specific default via this.getFieldInfo(fieldName)?.instance?.options.defaultValue into a local (e.g., fieldDefault) and use fieldDefault !== undefined ? fieldDefault : getBy(this.options.defaultValues, fieldName) when calling evaluate (change the occurrence inside evaluate and the similar occurrences around the 2601-2605 area) so explicit null values retain precedence.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
b1d96c6d-8ef2-4650-b68b-d363a041a5ea📥 Commits
Reviewing files that changed from the base of the PR and between cab9db4a45d7d79949f027933ca14d45e1006b77 and 51d50191277dd4a5be241afbe2f3327573165a55.
📒 Files selected for processing (4)
.changeset/gentle-jars-share.mdpackages/form-core/src/FormApi.tspackages/form-core/tests/FieldApi.spec.tspackages/form-core/tests/FormApi.spec.ts
@@ -0,0 +1,5 @@1+---2+'@tanstack/form-core': minor3+---4+5+Introduced a **Prioritized Default System** that ensures consistency between field metadata and form reset behavior. This change prioritizes field-level default values over form-level defaults across `isDefaultValue` derivation, `form.reset()`, and `form.resetField()`. This ensures that field metadata accurately reflects the state the form would return to upon reset and prevents `undefined` from being incorrectly treated as a default when a value is explicitly specified.⚠️ Potential issue | 🟠 Major | ⚡ Quick win
Recheck semver level for this behavioral precedence change.
This changes user-visible semantics of
isDefaultValue,reset(), andresetField(); consumers depending on previous dual-default behavior may break. Please confirm whether this should be amajorbump (or feature-flagged), notminor.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In @.changeset/gentle-jars-share.md around lines 2 - 5, The changeset claims a minor bump but introduces behavioral precedence altering user-visible semantics (Prioritized Default System) affecting isDefaultValue, form.reset(), and form.resetField(); re-evaluate and change the changeset to a major version bump or gate the behavior behind a feature flag/opt-in, update the .changeset text to reflect the decision, and ensure release notes explicitly document the behavioral change and migration guidance for consumers relying on previous dual-default behavior.@@ -1132,13 +1132,9 @@11321132 // As primitives, we don't need to aggressively persist the same referential value for performance reasons11331133 const isFieldValid = !isNonEmptyArray(fieldErrors)11341134 const isFieldPristine = !currBaseMeta.isDirty1135- const isDefaultValue =1136- evaluate(1137- curFieldVal,1135+ const isDefaultValue = evaluate(1136+ curFieldVal,1137+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition1138+ this.getFieldInfo(fieldName)?.instance?.options.defaultValue ??11381139 getBy(this.options.defaultValues, fieldName),1139- ) ||1140- evaluate(1141- curFieldVal,1142- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition1143- this.getFieldInfo(fieldName)?.instance?.options.defaultValue,1144- )1140+ )⚠️ Potential issue | 🟠 Major | ⚡ Quick win
nullfield defaults lose precedence due to??.Using nullish coalescing here makes explicit
defaultValue: nullfall back to form defaults, which breaks Field-over-Form priority and can desynchronize reset/default metadata behavior.Suggested fix
-const isDefaultValue = evaluate( - curFieldVal, - this.getFieldInfo(fieldName)?.instance?.options.defaultValue ?? - getBy(this.options.defaultValues, fieldName), -) +const fieldDefaultValue = + this.getFieldInfo(fieldName).instance?.options.defaultValue +const prioritizedDefaultValue = + fieldDefaultValue !== undefined + ? fieldDefaultValue + : getBy(this.options.defaultValues, fieldName) +const isDefaultValue = evaluate(curFieldVal, prioritizedDefaultValue)-const fieldDefault = - this.getFieldInfo(field).instance?.options.defaultValue -const formDefault = getBy(this.options.defaultValues, field) -const targetValue = fieldDefault ?? formDefault +const fieldDefault = + this.getFieldInfo(field).instance?.options.defaultValue +const formDefault = getBy(this.options.defaultValues, field) +const targetValue = fieldDefault !== undefined ? fieldDefault : formDefaultAlso applies to: 2601-2605
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/form-core/src/FormApi.ts` around lines 1135 - 1140, The code uses nullish coalescing (??) so an explicit field default of null is treated as missing and falls back to form defaults; update the logic in the evaluate call to treat only undefined as "missing" (preserve null/false/0 as valid defaults). Concretely, retrieve the field-specific default via this.getFieldInfo(fieldName)?.instance?.options.defaultValue into a local (e.g., fieldDefault) and use fieldDefault !== undefined ? fieldDefault : getBy(this.options.defaultValues, fieldName) when calling evaluate (change the occurrence inside evaluate and the similar occurrences around the 2601-2605 area) so explicit null values retain precedence.crutchcorn(GitHub profile, opens in a new tab) approved these changes
This looks really good. Thank you for the thoughtful PR and description; sorry that it took me so long to review + merge.
Just as a heads up, @LeCarbonator is considering some changes to
defaultValuein a field for v2. Namely removing it outright. Would love to hear your feedback on that idea as someone who's clearly thought about field-first default values.crutchcorn(GitHub profile, opens in a new tab) closed this
@crutchcorn Thanks so much, and no worries on the timing!
I’ve picked up on bits of the related conversations around field-level vs form-level defaults, so dropping field-level defaultValue in v2 sounds like a reasonable direction from where I’m sitting. Would love to contribute to that effort in whatever capacity is useful — just let me know where the discussion lives and I’ll join in.
Sign in to join this conversation.
🦋 Changeset detected#
Latest commit: 699134cd69f0819b1b27d0d10567aa5d60049fd7
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 13 packages
Not sure what this means? Click here to learn what changesets are.
Click here if you're a maintainer who wants to add another changeset to this PR