nextjs-tanstack-form

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TanStack Form for Next.js 16

适用于Next.js 16的TanStack Form

Type-safe, performant forms with Server Actions and signal-based reactivity.
具备Server Actions和基于信号的响应式特性的类型安全、高性能表单。

Agent Workflow (MANDATORY)

Agent工作流(强制要求)

Before ANY implementation, use
TeamCreate
to spawn 3 agents:
  1. fuse-ai-pilot:explore-codebase - Analyze existing forms and validation patterns
  2. fuse-ai-pilot:research-expert - Verify latest TanStack Form docs via Context7/Exa
  3. mcp__context7__query-docs - Check form options and field API
After implementation, run fuse-ai-pilot:sniper for validation.

在进行任何实现之前,使用
TeamCreate
生成3个Agent:
  1. fuse-ai-pilot:explore-codebase - 分析现有表单和验证模式
  2. fuse-ai-pilot:research-expert - 通过Context7/Exa验证TanStack Form的最新文档
  3. mcp__context7__query-docs - 检查表单选项和字段API
实现完成后,运行fuse-ai-pilot:sniper进行验证。

Overview

概述

When to Use

适用场景

  • Building forms with complex validation requirements
  • Need Server Actions integration for form submission
  • Implementing multi-step wizards or dynamic field arrays
  • Require real-time async validation (username availability)
  • Want type-safe forms with full TypeScript inference
  • 构建具备复杂验证需求的表单
  • 需要集成Server Actions处理表单提交
  • 实现多步骤向导或动态字段数组
  • 需要实时异步验证(如用户名可用性检查)
  • 希望使用具备完整TypeScript类型推断的类型安全表单

Why TanStack Form

选择TanStack Form的理由

FeatureBenefit
Signal-based stateMinimal re-renders, optimal performance
Full TypeScriptDeepKeys, DeepValue inference
Server Actions nativeBuilt-in Next.js 16 integration
Zod adapterSchema-first validation
Framework agnosticSame API for React, Vue, Solid
HeadlessWorks with any UI library (shadcn/ui)

特性优势
基于信号的状态管理最少重渲染,最优性能
完整TypeScript支持DeepKeys、DeepValue类型推断
原生支持Server Actions内置Next.js 16集成
Zod适配器基于Schema的优先验证
框架无关React、Vue、Solid使用相同API
无头组件可与任意UI库(如shadcn/ui)配合使用

Critical Rules

关键规则

  1. formOptions shared - Define once, use in client and server
  2. Server validation - DB checks in
    onServerValidate
    , not client
  3. Zod schemas - Client-side instant feedback
  4. useActionState - React 19 hook for Server Actions
  5. mergeForm - Combine server errors with client state
  6. SOLID paths - Forms in
    modules/[feature]/src/components/forms/

  1. 共享formOptions - 仅定义一次,同时用于客户端和服务端
  2. 服务端验证 - 数据库检查放在
    onServerValidate
    中,而非客户端
  3. Zod Schema - 客户端即时反馈
  4. useActionState - 用于Server Actions的React 19钩子
  5. mergeForm - 合并服务端错误与客户端状态
  6. SOLID路径规范 - 表单存放在
    modules/[feature]/src/components/forms/
    目录下

SOLID Architecture

SOLID架构

Module Structure

模块结构

Forms organized by feature module:
  • modules/auth/src/components/forms/
    - Auth forms (login, signup)
  • modules/auth/src/interfaces/
    - Form types and schemas
  • modules/auth/src/actions/
    - Server Actions for form submission
  • modules/cores/lib/forms/
    - Shared form utilities
表单按功能模块组织:
  • modules/auth/src/components/forms/
    - 认证表单(登录、注册)
  • modules/auth/src/interfaces/
    - 表单类型与Schema
  • modules/auth/src/actions/
    - 处理表单提交的Server Actions
  • modules/cores/lib/forms/
    - 共享表单工具类

File Organization

文件组织

FilePurposeMax Lines
form-options.ts
Shared formOptions + Zod schema50
FormComponent.tsx
Client form UI with fields80
form.action.ts
Server Action with validation30
form.interface.ts
Types for form values30

文件用途最大行数
form-options.ts
共享formOptions + Zod Schema50
FormComponent.tsx
包含字段的客户端表单UI80
form.action.ts
带验证的Server Action30
form.interface.ts
表单值的类型定义30

Key Concepts

核心概念

Form Options Pattern

表单选项模式

Define form configuration once, share between client and server. Ensures type safety and consistency.
仅定义一次表单配置,在客户端和服务端共享。确保类型安全和一致性。

Field API

字段API

Each field has state (value, errors, touched, validating) and handlers (handleChange, handleBlur).
每个字段都有状态(值、错误、已触碰、验证中)和处理函数(handleChange、handleBlur)。

Validation Levels

验证层级

  • onChange - Real-time as user types
  • onBlur - When field loses focus
  • onSubmit - Before form submission
  • onServer - Server-side in action
  • onChange - 用户输入时实时验证
  • onBlur - 字段失去焦点时验证
  • onSubmit - 表单提交前验证
  • onServer - 在服务端Action中验证

Error Management

错误管理

Errors exist at field-level and form-level. Use
field.state.meta.errors
for field errors,
form.state.errorMap
for form errors.

错误分为字段级和表单级。使用
field.state.meta.errors
获取字段错误,使用
form.state.errorMap
获取表单错误。

Reference Guide

参考指南

NeedReference
Initial setupinstallation.md
Basic patternsbasic-usage.md, field-api.md
Validationvalidation-zod.md, async-validation.md
Server Actionsserver-actions.md
Dynamic formsarray-fields.md, multi-step-form.md
UI integrationshadcn-integration.md
TypeScripttypescript.md
Migrationmigration-rhf.md

需求参考文档
初始设置installation.md
基础模式basic-usage.md, field-api.md
验证validation-zod.md, async-validation.md
Server Actionsserver-actions.md
动态表单array-fields.md, multi-step-form.md
UI集成shadcn-integration.md
TypeScripttypescript.md
迁移migration-rhf.md

Best Practices

最佳实践

  1. Define schemas first - Zod schemas drive both validation and types
  2. Shared formOptions - Single source of truth for client/server
  3. Debounce async validation - Use
    asyncDebounceMs
    for API calls
  4. form.Subscribe - Selective re-renders for submit state
  5. Field composition - Reusable field components with shadcn/ui
  6. Server errors merge - Use
    mergeForm
    to show server validation errors

  1. 优先定义Schema - Zod Schema同时驱动验证和类型定义
  2. 共享formOptions - 客户端/服务端的单一事实来源
  3. 防抖异步验证 - 对API调用使用
    asyncDebounceMs
  4. form.Subscribe - 针对提交状态的选择性重渲染
  5. 字段组合 - 基于shadcn/ui的可复用字段组件
  6. 服务端错误合并 - 使用
    mergeForm
    展示服务端验证错误

Comparison vs React Hook Form

与React Hook Form的对比

AspectTanStack FormReact Hook Form
Type Safety100% (DeepKeys)Manual typing
PerformanceSignals (minimal)Refs (good)
Server ActionsNative supportManual integration
Bundle Size~12KB~9KB
Learning CurveMediumLow
Use CaseComplex appsStandard forms
维度TanStack FormReact Hook Form
类型安全100%(DeepKeys)手动类型定义
性能基于信号(重渲染极少)基于Ref(良好)
Server Actions支持原生支持手动集成
包体积~12KB~9KB
学习曲线中等
适用场景复杂应用标准表单