Skip to content
Skills Library
Programming · Learning & explanation

TanStack Forms

/TanStack Forms

This skill should be used when the user asks about "React Query with forms", "form submission with useMutation", "form state vs server state", "defaultValue from query", "form reset after mutation", "double submit prevention", or needs guidance on integrating TanStack Query with forms.

Repository
brain-dump ↗
Licence
MIT
Last repository change
22.10.2026

Assessment and security

90/ 100Class: good
Format15 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
2
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 22.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

This skill should be used when the user asks about "React Query with forms", "form submission with useMutation", "form state vs server state", "defaultValue from query", "form reset after mutation", "double submit prevention", or needs guidance on integrating TanStack Query with forms.

Triggers from the description

React Query with formsform submission with useMutationform state vs server statedefaultValue from queryform reset after mutationdouble submit prevention
Original author description

This skill should be used when the user asks about "React Query with forms", "form submission with useMutation", "form state vs server state", "defaultValue from query", "form reset after mutation", "double submit prevention", or needs guidance on integrating TanStack Query with forms.

How it works

  1. The Core Challenge
  2. Two Main Approaches
  3. Essential Patterns
  4. Preventing Stale Data Issues
  5. Quick Reference
  6. Common Mistakes
  7. Additional Resources
Original SKILL.md headings · 348 lines, 1,128 words
SKILL.md preview
---
name: TanStack Forms
description: This skill should be used when the user asks about "React Query with forms", "form submission with useMutation", "form state vs server state", "defaultValue from query", "form reset after mutation", "double submit prevention", or needs guidance on integrating TanStack Query with forms.
version: 1.0.0
---

# TanStack Query Forms Integration Patterns

This skill provides guidance for integrating TanStack Query with forms, covering the challenge of mixing server state with form (client) state, based on TKDodo's recommendations.

## The Core Challenge

Form data exists in a hybrid zone:
- **Initially**: Server State (fetched data)
- **During editing**: Client State (user changes)
- **After submit**: Server State again

Understanding this lifecycle is key to choosing the right pattern.

## Two Main Approaches

### Approach 1: Simple - Copy to Form State

Use server state as initial data only. The form manages its own state:

```typescript
function EditTodo({ id }: { id: string }) {
  const { data: todo, isLoading } = useQuery(todoQueries.detail(id))

  if (isLoading) return <Skeleton />

  return <TodoForm initialData={todo} />
}

function TodoForm({ initialData }: { initialData: Todo }) {
  // Form state is independent copy of server state
  const [title, setTitle] = useState(initialData.title)
  const [description, setDescription] = useState(initialData.description)

  const mutation = useMutation({
    mutationFn: (data: Partial<Todo>) =>
      api.patch(`/todos/${initialData.id}`, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['todos'] })
    },
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    mutation.mutate({ title, description })
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={title}
        onChange={(e) => setTitle(e.target.value)}
      />
      <textarea
        value={description}
        onChange={(e) => setDescription(e.target.value)}
      />
      <button type="submit" disabled={mutation.isPending}>
        Save
      </button>
    </form>
  )
}
```

**Pros:**
- Simple to understand
- Form is in full control
- Works with any form library

**Cons:**
- Background updates won't reflect in form
- Can lead to stale data submission in collaborative apps

**Best for:** Single-user apps, short-lived forms, simple editing flows

### Approach 2: Derived State Pattern

Keep server state and form state separate, display whichever is relevant:

```typescript
function EditTodo({ id }: { id: string }) {
  const { data: serverTodo } = useQuery(todoQueries.detail(id))

  // Track which fields user has changed
  const [formChanges, setFormChanges] = useState<Partial<Todo>>({})

  // Derived state: show user changes, fall back to server data
  const displayedTodo = {
    ...serverTodo,
    ...formChanges, // User changes override server data
  }

  const mutation = useMutation({
    mutationFn: (data: Partial<Todo>) => api.patch(`/todos/${id}`, data),
    onSuccess: () => {
      // Clear form changes after successful save
      setFormChanges({})
      queryClient.invalidateQueries({ queryKey: ['todos', id] })
    },
  })

  const handleFieldChange = (field: keyof Todo, value: string) => {
    setFormChanges((prev) => ({ ...prev, [field]: value }))
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    mutation.mutate(formChanges)
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={displayedTodo?.title ?? ''}
        onChange={(e) => handleFieldChange('title', e.target.value)}
      />
      {/* Fields user hasn't touched will update from server */}
    </form>
  )
}
```

**Pros:**
- Background updates visible for untouched fields
- Better for collaborative editing
- Server is always source of truth

**Cons:**
- More complex state management
- Requires controlled components
- Must track changed fields

**Best for:** Collaborative apps, long-lived forms, real-time environments

## Essential Patterns

### Double Submit Prevention

Always disable submit during mutation:

```typescript
const mutation = useMutation({
  mutationFn: createTodo,
})

<button
  type="submit"
  disabled={mutation.isPending}
>
  {mutation.isPending ? 'Saving...' : 'Save'}
</button>
```

### Form Reset After Mutation

Reset form state to allow server state to show through:

```typescript
const [formData, setFormData] = useState<Partial<Todo>>({})

const mutation = useMutation({
  mutationFn: (data: Partial<Todo>) => api.patch(`/todos/${id}`, data),
  onSuccess: () => {
    // 1. Invalidate to get fresh server data
    queryClient.invalidateQueries({ queryKey: ['todos', id] })
    // 2. Clear form state so server state shows
    setFormData({})
  },
})
```

### Component Splitting for Initialization

Separate data fetching from form rendering to properly initialize `defaultValue`:

```typescript
// Wrapper handles loading state
function EditTodoPage({ id }: { id: string }) {
  const { data, isLoading, error } = useQuery(todoQueries.detail(id))

  if (isLoading) return <FormSkeleton />
  if (error) return <ErrorDisplay error={error} />
  if (!data) return null

  // Form only renders when data exists
  return <TodoForm todo={data} />
}

// Form receives guaranteed data
function TodoForm({ todo }: { todo: Todo }) {
  // Safe to use as defaultValue - todo is guaranteed
  return (
    <form>
      <input defaultValue={todo.title} name="title" />
      <textarea defaultValue={todo.description} name="description" />
    </form>
  )
}
```

### Using with React Hook Form

```typescript
import { useForm } from 'react-hook-form'

function TodoForm({ todo }: { todo: Todo }) {
  const { register, handleSubmit, reset } = useForm({
    defaultValues: todo,
  })

  const mutation = useMutation({
    mutationFn: (data: Todo) => api.patch(`/todos/${todo.id}`, data),
    onSuccess: (updatedTodo) => {
      queryClient.invalidateQueries({ queryKey: ['todos'] })
      // Reset form to new server values
      reset(updatedTodo)
    },
  })

  return (
    <form onSubmit={handleSubmit((data) => mutation.mutate(data))}>
      <input {...register('title')} />
      <textarea {...register('description')} />
      <button type="submit" disabled={mutation.isPending}>
        Save
      </button>
    </form>
  )
}
```

## Preventing Stale Data Issues

### Option 1: Disable Background Refetch

For the simple approach, prevent confusing UX:

```typescript
const { data } = useQuery({
  ...todoQueries.detail(id),
  staleTime: Infinity, // Don't refetch while editing
  refetchOnWindowFocus: false, // Don't refetch on tab focus
})
```

### Option 2: Warn About Conflicts

For collaborative apps, detect and warn:

```typescript
function EditTodo({ id }: { id: string }) {
  const { data: serverTodo, dataUpdatedAt } = useQuery(todoQueries.detail(id))
  const [formData, setFormData] = useState<Partial<Todo>>({})
  const [formStartedAt] = useState(Date.now())

  // Detect if server data changed while editing
  const hasConflict = dataUpdatedAt > formStartedAt && Object.keys(formData).length > 0

  return (
    <form>
      {hasConflict && (
        <Alert>
          This item was updated. Review changes before saving.
          <button onClick={() => setFormData({})}>
            Discard my changes
          </button>
        </Alert>
      )}
      {/* Form fields */}
    </form>
  )
}
```

## Quick Reference

| Scenario | Pattern |
|----------|---------|
| Simple edit form | Copy to state, staleTime: Infinity |
| Collaborative editing | Derived state pattern |
| Create form | Standard mutation, no query needed |
| With form library | Split loading/form components |
| Long-lived form | Conflict detection |

## Common Mistakes

### 1. Using Query Data Directly as Form State

```typescript
// BAD: Query data changes unexpectedly
const { data } = useQuery(todoQueries.detail(id))

return (
  <input
    value={data?.title} // Changes on refetch!
    onChange={(e) => /* where does this go? */}
  />
)
```

### 2. Not Handling Loading State Before Form

```typescript
// BAD: defaultValue is undefined
function Form({ id }) {
  const { data } = useQuery(todoQueries.detail(id))

  return <input defaultValue={data?.title} /> // undefined on first render!
}

// GOOD: Split components
function FormWrapper({ id }) {
  const { data, isLoading } = useQuery(todoQueries.detail(id))
  if (isLoading || !data) return <Loading />
  return <Form todo={data} />
}
```

### 3. Forgetting to Reset Form on Success

```typescript
// BAD: Old form data persists after save
onSuccess: () => {
  queryClient.invalidateQueries({ queryKey: ['todos'] })
  // Form still shows old local state!
}

// GOOD: Reset form state
onSuccess: (newData) => {
  queryClient.invalidateQueries({ queryKey: ['todos'] })
  setFormState({}) // or reset(newData) with RHF
}
```

## Additional Resources

### Reference Files

For detailed patterns and advanced techniques, consult:
- **`references/form-library-integration.md`** - Patterns with React Hook Form, Formik

### Related Skills

- **tanstack-mutations** - Mutation patterns for form submission
- **tanstack-query** - Query patterns for loading initial data
- **tanstack-errors** - Handling form submission errors
Files in this package (2)
  • SKILL.md 9 KB
  • references/form-library-integration.md 9 KB

Versions

The database has no other skills named TanStack Forms.

Database snapshot: 13.11.2026 · package version 06517b5115c1 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 90tanstack-react-query-best-practices
    TanStack Query conventions for cache-backed React server state. Use when creating or reviewing React queries, mutations, query keys, or cache updates.
  • 90tanstack-react-query-best-practices
    TanStack Query conventions for cache-backed React server state. Use when creating or reviewing React queries, mutations, query keys, or cache updates.
  • 100tanstack-query
    TanStack Query v5 performance optimization for data fetching, caching, mutations, and query patterns. This skill should be used when using useQuery, useMutation, queryClient, prefetch patterns, or TanStack Query caching. This skill does NOT cover generating query hooks from…
  • 90TanStack Errors
    This skill should be used when the user asks about "React Query error handling", "error boundaries with useQuery", "throwOnError", "global error callbacks", "onError callback", "query error state", "mutation error handling", or needs guidance on error handling strategies and…
  • 100frontend-query-mutation
    Guide for implementing Langflow frontend query and mutation patterns with Axios and TanStack React Query v5. Trigger when creating or updating API hooks in controllers/API/queries, consuming UseRequestProcessor in components, deciding whether to use useQuery or useMutation,…
  • 95tanstack-query-best-practices
    TanStack Query (React Query) best practices for data fetching, caching, mutations, and server state management. Activate when building data-driven React applications with server state.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.