Skip to content

fix(react-form): use fresh FieldApi in current render on name change#2240

Merged
crutchcorn merged 2 commits into
TanStack:mainfrom
xianjianlf2:fix/keyed-field-stale-on-array-removal-2238
Jul 13, 2026
Merged

fix(react-form): use fresh FieldApi in current render on name change#2240
crutchcorn merged 2 commits into
TanStack:mainfrom
xianjianlf2:fix/keyed-field-stale-on-array-removal-2238

Conversation

@xianjianlf2

@xianjianlf2 xianjianlf2 commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

Closes #2238

Regression from #1893 (v1.27.0). On a name/form change, useField calls setFieldApi(new FieldApi(...)) during render but the current render keeps using the stale fieldApi state. React discards that render, yet the render prop still runs once against the stale FieldApi's store — which derives undefined for an array index that no longer exists after a removal, crashing strict render code.

Fix applies the canonical "adjust-state-during-render + local variable" pattern: build the new instance, use it for the rest of the current render, and still setFieldApi it (keeping the setState identity #1893 introduced for React Compiler safety) — restoring pre-1.27.0 correctness.

  • Added a test that keys array items by stable id, removes a non-last item, and asserts the subfield never observes undefined; fails before, passes after.
  • pnpm vitest run (react-form) → 126 passed, no type errors.

Summary by CodeRabbit

  • Bug Fixes
    • Fixed field state updates to ensure the current render uses the correct field instance when the form or field name changes.
    • Prevented array-field subfield values from temporarily becoming undefined when removing an item from a stably keyed, shifted (non-last) element.
    • Ensured remaining array items keep displaying the correct values after removals.
  • Tests
    • Added a regression test covering stable, keyed array fields when items are removed.

When a field's `name` changes (e.g. a non-last item is removed from a
stably-keyed array), `useField` created a new FieldApi via
`setFieldApi` during render but continued the current render pass with
the stale instance. React discards that pass, but the render prop still
runs to completion once with the stale FieldApi, whose store derives
`undefined` for the path that no longer exists at the old index. This
briefly surfaces `state.value === undefined` for surviving array items,
crashing render code that treats the value strictly.

Adjust state during render but also use the freshly created FieldApi for
the remainder of this render, so the field reads state at its current
`name`. Keeps the setState-based identity (React Compiler safe) while
restoring the pre-1.27.0 behavior.

Closes TanStack#2238
@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

useField now uses a newly created FieldApi immediately when its form or name changes. A regression test verifies that removing the first item from a stably keyed array preserves the shifted field value without transient undefined state.

Changes

FieldApi synchronization

Layer / File(s) Summary
Synchronous FieldApi replacement and regression coverage
packages/react-form/src/useField.tsx, packages/react-form/tests/useField.test.tsx, .changeset/hot-sides-fetch.md
useField uses the replacement FieldApi during the current render and stores that same instance in state. The test verifies correct values and no undefined observations after removing a non-last keyed array item, and the changeset records a patch release.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: crutchcorn, lecarbonator

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main fix: using a fresh FieldApi during render when the field name changes.
Description check ✅ Passed The description explains the bug, fix, test coverage, and validation, though it omits the template's explicit checklist and release-impact formatting.
Linked Issues check ✅ Passed The changes match #2238 by avoiding stale FieldApi state on name changes and adding a regression test for shifted array items.
Out of Scope Changes check ✅ Passed The PR stays focused on the FieldApi render fix, its regression test, and the required changeset; no unrelated changes are present.
✨ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@crutchcorn crutchcorn left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting fix. Very subtle. Assuming tests fix, I'll merge. Thanks!

@nx-cloud

nx-cloud Bot commented Jul 13, 2026

Copy link
Copy Markdown

View your CI Pipeline Execution ↗ for commit 09b74ac

Command Status Duration Result
nx affected --targets=test:sherif,test:knip,tes... ✅ Succeeded 58s View ↗
nx run-many --target=build --exclude=examples/** ✅ Succeeded 5s View ↗

☁️ Nx Cloud last updated this comment at 2026-07-13 04:09:03 UTC

@pkg-pr-new

pkg-pr-new Bot commented Jul 13, 2026

Copy link
Copy Markdown
More templates

@tanstack/angular-form

npm i https://pkg.pr.new/@tanstack/angular-form@2240

@tanstack/form-core

npm i https://pkg.pr.new/@tanstack/form-core@2240

@tanstack/form-devtools

npm i https://pkg.pr.new/@tanstack/form-devtools@2240

@tanstack/lit-form

npm i https://pkg.pr.new/@tanstack/lit-form@2240

@tanstack/preact-form

npm i https://pkg.pr.new/@tanstack/preact-form@2240

@tanstack/react-form

npm i https://pkg.pr.new/@tanstack/react-form@2240

@tanstack/react-form-devtools

npm i https://pkg.pr.new/@tanstack/react-form-devtools@2240

@tanstack/react-form-nextjs

npm i https://pkg.pr.new/@tanstack/react-form-nextjs@2240

@tanstack/react-form-remix

npm i https://pkg.pr.new/@tanstack/react-form-remix@2240

@tanstack/react-form-start

npm i https://pkg.pr.new/@tanstack/react-form-start@2240

@tanstack/solid-form

npm i https://pkg.pr.new/@tanstack/solid-form@2240

@tanstack/solid-form-devtools

npm i https://pkg.pr.new/@tanstack/solid-form-devtools@2240

@tanstack/svelte-form

npm i https://pkg.pr.new/@tanstack/svelte-form@2240

@tanstack/vue-form

npm i https://pkg.pr.new/@tanstack/vue-form@2240

commit: 374b4d9

@codecov-commenter

codecov-commenter commented Jul 13, 2026

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 64.95%. Comparing base (6892ed0) to head (374b4d9).
⚠️ Report is 257 commits behind head on main.
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files
@@             Coverage Diff             @@
##             main    #2240       +/-   ##
===========================================
- Coverage   90.35%   64.95%   -25.41%     
===========================================
  Files          38       19       -19     
  Lines        1752      311     -1441     
  Branches      444       48      -396     
===========================================
- Hits         1583      202     -1381     
+ Misses        149       94       -55     
+ Partials       20       15        -5     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 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/hot-sides-fetch.md:
- Line 5: Update the changeset note to mention that a fresh FieldApi is used
when either the form or field name changes, accurately covering both triggers
addressed by the implementation.
🪄 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: 4f6404e0-1ff7-457a-b6b0-2840a30beb3e

📥 Commits

Reviewing files that changed from the base of the PR and between 09b74ac and 374b4d9.

📒 Files selected for processing (1)
  • .changeset/hot-sides-fetch.md

'@tanstack/react-form': patch
---

Use fresh FieldApi in current render on name change

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Mention form changes as well

The implementation refreshes FieldApi when either form or name changes, but this changeset only documents name changes. Please update the note so the published changelog accurately describes the fix.

Proposed wording
-Use fresh FieldApi in current render on name change
+Use fresh FieldApi in current render on form or name change
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Use fresh FieldApi in current render on name change
Use fresh FieldApi in current render on form or name change
🤖 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/hot-sides-fetch.md at line 5, Update the changeset note to
mention that a fresh FieldApi is used when either the form or field name
changes, accurately covering both triggers addressed by the implementation.

@crutchcorn crutchcorn merged commit d756476 into TanStack:main Jul 13, 2026
9 checks passed
@github-actions github-actions Bot mentioned this pull request Jul 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fields in uuid-keyed array items transiently go undefined on removal again: #1729 fixed it in 1.26.0, #1893 regressed it in 1.27.0

3 participants