Tutorial TypeScript React

How to Combine TanStack Query, Table, Form, and Virtual in One React App

A practical walk through a public demo that composes TanStack Query, Form, Table, Virtual, and Store in one TanStack Start app, including optimistic updates and a real limitation in the virtual list.

Dao Quang Truong
7 min read
On this page tap to expand

Each TanStack library is easy to try on its own. The hard part starts when one screen has to fetch data, edit it, and render a large list without the cache and the form fighting each other.

This tutorial walks through a public demo that puts those libraries in one tree: TanStack Query for the server cache, TanStack Form for validated input, TanStack Table for sort, filter, and pagination, TanStack Virtual for a long list, and TanStack Store for a little shared UI state. Routing and SSR come from TanStack Start and TanStack Router. Follow along in the demo at example-react-brown.vercel.app or in the source at github.com/2tsoftwareapp/example-react.

By the end, you will know how the seams work: optimistic cache updates next to a form, a table and a virtual list over the same query, and a store that does not pretend to be your server state.

What the Demo App Contains

The app is a small dashboard with three routes:

  • /todos uses Query, Form, and Store. You can add, toggle, and delete todos with optimistic updates, and a global search box filters the list.
  • /posts uses Query, Table, and Virtual. One query loads 100 posts and caches them for ten minutes. You can switch between a sortable, pageable table and a virtualized list.
  • /users uses Query, Table, and Form: a filterable table, plus an edit dialog that submits through a mutation.

The UI is shadcn/ui and Tailwind CSS v4. Data comes from JSONPlaceholder. That API accepts POST, PATCH, and DELETE and returns a plausible response, but it does not persist writes. Reload the page and the original data comes back. The optimistic UI is still worth studying; do not treat the API as a real backend.

The repo README, at the time of writing, listed Query 5, Table 8, Virtual 3, Form 1, Store 0.9, Router 1, and Start 1. Check package.json before you copy the demo.

Keep Server State in Query, and UI State in a Store

Start by splitting server state from UI state. Todos, posts, and users are server state: they have a query key, a queryFn, and (for writes) a mutation. The search string and the posts view mode (table or virtual) are UI state. The demo keeps those in a TanStack Store:

import { Store } from '@tanstack/store'

export const appStore = new Store({
  activeTab: 'todos',
  viewMode: 'table',
  searchQuery: '',
})

export function setSearchQuery(q: string) {
  appStore.setState((s) => ({ ...s, searchQuery: q }))
}

A component subscribes with a selector, for example useStore(appStore, (s) => s.searchQuery). Query still owns the list of todos; the store only holds the client-side filter string.

Add a Todo Without Waiting for the Server

On the todos page, fetch is a normal useQuery. Creates, toggles, and deletes are useMutation hooks that update the cache in onMutate, roll it back in onError, and change the UI before the response arrives.

The add path, trimmed from src/routes/todos.tsx, looks like this:

const queryClient = useQueryClient()

const addMutation = useMutation({
  mutationFn: async (title: string) => {
    const res = await fetch('https://jsonplaceholder.typicode.com/todos', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title, completed: false, userId: 1 }),
    })
    return res.json()
  },
  onMutate: async (title) => {
    await queryClient.cancelQueries({ queryKey: ['todos'] })
    const prev = queryClient.getQueryData(['todos'])
    const optimistic = { id: Date.now(), userId: 1, title, completed: false }
    queryClient.setQueryData(['todos'], (old) => [optimistic, ...(old ?? [])])
    return { prev }
  },
  onError: (_err, _title, ctx) => {
    if (ctx?.prev) queryClient.setQueryData(['todos'], ctx.prev)
  },
})

Copy three details into your own apps:

  1. cancelQueries stops an in-flight fetch from overwriting the optimistic list.
  2. onMutate returns the previous cache snapshot so onError can restore it.
  3. The temporary id is a client-side stand-in. Against a real API you would usually replace that row with the server id in onSuccess. This demo skips that swap, which is fine for a fake API and a gap you should close in production.

The Query guide on optimistic updates is the right companion to this pattern.

Let the Form Own Validation, Then Hand Off to the Mutation

The add field is not a raw useState. TanStack Form owns validation and submit, then it calls the mutation:

const form = useForm({
  defaultValues: { title: '' },
  onSubmit: async ({ value, formApi }) => {
    if (!value.title.trim()) return
    addMutation.mutate(value.title.trim())
    formApi.reset()
  },
})

The title field uses an onChange validator that returns "Title is required" when the value is empty. The input reads field.state.value, writes through field.handleChange, and shows field.state.meta.errors after blur. The mutation does not need those field details. Form is for input quality; Query is for server state.

Resetting the form right after mutate matches the optimistic model: the new row is already in the list. If you need the request to succeed first, wait on mutateAsync and then call reset.

Switch a Table and a Virtual List Over the Same Query

The posts route runs one query for all posts, with staleTime set to ten minutes so a return visit does not refetch immediately. That same array then feeds two presentations.

TanStack Table is headless: you pass data, columns, and row-model helpers, and you render the markup. The demo turns on sorting, a global filter, and pagination (ten rows per page):

const table = useReactTable({
  data: posts,
  columns,
  state: { sorting, globalFilter },
  onSortingChange: setSorting,
  onGlobalFilterChange: setGlobalFilter,
  getCoreRowModel: getCoreRowModel(),
  getSortedRowModel: getSortedRowModel(),
  getFilteredRowModel: getFilteredRowModel(),
  getPaginationRowModel: getPaginationRowModel(),
  initialState: { pagination: { pageSize: 10 } },
})

When the store’s viewMode is virtual, the page uses useVirtualizer. Only the visible rows, plus a small overscan, exist in the DOM. The list is a 500px scroll container. The inner element’s height is rowVirtualizer.getTotalSize(), and each item is positioned with translateY:

const parentRef = React.useRef(null)
const rowVirtualizer = useVirtualizer({
  count: posts.length,
  getScrollElement: () => parentRef.current,
  estimateSize: () => 72,
  overscan: 5,
})

One limitation of this demo: the virtual list iterates posts, not the table’s filtered or sorted row model. The two views share the query, but not sort and filter state. If you reuse the pattern, pass table.getRowModel().rows (or a memoized filtered array) into the virtualizer so both views stay consistent.

The Virtual documentation covers dynamic row height if your rows are not a fixed 72px.

What to Watch For When You Compose These Libraries

A few rules of thumb fall out of this demo:

  • Give Query a stable queryKey per resource (['todos'], ['posts'], ['users']) and keep mutations on the same key family.
  • Do not treat Store or Form default values as the source of truth for server records. Copy a row into a form when a dialog opens, then write back through a mutation.
  • Optimistic updates need a rollback path. A fake API that always “succeeds” will hide bugs a flaky backend will show you.
  • Headless table and virtualizer APIs make composition possible because you own the markup. Shared sort, filter, and selection state is still your job unless you wire it explicitly.
  • JSONPlaceholder is fine for teaching. In production, use your API, handle the real id on create, and decide when to invalidate versus patch the cache.

Conclusion

You do not need a single “TanStack mega hook” to build a credible dashboard. You need a clear split: Query for server cache and mutations, Form for input and validation, Table and Virtual for two ways to render the same list, and a small Store for UI flags. The example-react demo is a compact place to see those seams, including the limits of a read-mostly fake API.

If you want to go further, read the guides for optimistic updates, TanStack Table, and TanStack Virtual. Then try one improvement: share sort and filter state between the table and the virtual list, or replace JSONPlaceholder with an API that persists writes.

Related Articles