React Query, react-hook-form and Zod: updating data after a form save
Keeping server data apart from form drafts, consistent query keys, cache updates after a mutation, and API errors shown under the right form field.
You save a form and the toast confirms it, but the list behind the modal still shows the old value. The mutation finished fine, but the list's query was never marked stale. I use TanStack Query v5 for server data, react-hook-form for values being edited and Zod for validation, and the fragile parts are where the three have to line up.
Examples use @tanstack/react-query 5.10x, react-hook-form 7.7x/7.8x, zod 4 and @hookform/resolvers 5, with notes for zod 3.24 and resolvers 3.10, which a project I maintain still runs.
Server data goes in the cache, the draft goes in the form
Server state goes stale on its own and other people change it. TanStack Query keeps it, react-hook-form keeps what's being edited, and an open modal or selected tab goes in useState. I don't copy query results into useState or a global store, because the two copies will drift sooner or later.
A key factory so server and client share one key
I once touched 26 files just to make keys consistent. A detail query used the list's key, and a hand-typed string key had to match between server prefetch and client hook. When keys disagree, hydration silently does nothing and the client fetches again without any warning. A key factory paired with queryOptions removes that kind of bug:
import { queryOptions } from '@tanstack/react-query';
import { getTodo, listTodos, type TodoFilters } from './api';
export const todoKeys = {
all: ['todos'] as const,
lists: () => [...todoKeys.all, 'list'] as const,
list: (filters: TodoFilters) => [...todoKeys.lists(), filters] as const,
details: () => [...todoKeys.all, 'detail'] as const,
detail: (id: string) => [...todoKeys.details(), id] as const,
};
export const todoQueries = {
list: (filters: TodoFilters) =>
queryOptions({
queryKey: todoKeys.list(filters),
queryFn: () => listTodos(filters),
}),
detail: (id: string) =>
queryOptions({
queryKey: todoKeys.detail(id),
queryFn: () => getTodo(id),
staleTime: 60_000,
}),
};
useQuery, prefetchQuery and getQueryData now share one key, and TypeScript knows the data type in all three. todoKeys.lists() matches each filtered list, todoKeys.all matches anything todo-related. Filters go in as one object, since key hashing ignores property order. Anything the queryFn reads belongs in the key, or page 2 shows page 1's cached data.
The v5 default is staleTime: 0, and every remount of a cached query starts a background refetch. I set it per query: an hour for a country list, 30 to 60 seconds for normal entities. With server rendering, staleTime has to be above zero. Otherwise hydrated data is stale on arrival and the prefetch is wasted.
The server creates a new QueryClient per request so one user's cache can't leak into another's response, and the browser keeps one. In Next.js I prefetch in a Server Component and wrap the client tree in HydrationBoundary. Don't use Server Actions as a queryFn. The Next.js docs say they're queued, so your queries end up running one after another.
After a mutation, invalidate first and go optimistic only when needed
Most of the time I just invalidate todoKeys.lists() in onSettled. Returning that promise keeps the mutation isPending until the refetch finishes, and the submit button is disabled until the list has updated. That's usually enough. If the server returns the full entity, setQueryData saves the detail view a request, while lists with sorting, filters and pagination still get invalidated. After a create in an infinite list, resetQueries clears the old feed instead of showing it while each page refetches.
Optimistic updates suit requests that almost never fail and need instant feedback, like toggles, likes and deletes. The order is always the same. Cancel in-flight fetches, snapshot the cache, write the new value, roll back on error, then sync with the server:
export function useToggleTodo() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (todo: Todo) => updateTodo(todo.id, { done: !todo.done }),
onMutate: async (todo) => {
// Stop in-flight refetches from overwriting the optimistic value
await queryClient.cancelQueries({ queryKey: todoKeys.all });
// Snapshot every entry we are about to touch, not just one
const snapshot = queryClient.getQueriesData({ queryKey: todoKeys.all });
const flip = (t: Todo) => (t.id === todo.id ? { ...t, done: !t.done } : t);
queryClient.setQueriesData<TodoPage>({ queryKey: todoKeys.lists() }, (old) =>
old ? { ...old, items: old.items.map(flip) } : old,
);
queryClient.setQueryData<Todo>(todoKeys.detail(todo.id), (old) =>
old ? flip(old) : old,
);
return { snapshot };
},
onError: (_error, _todo, onMutateResult) => {
onMutateResult?.snapshot.forEach(([key, data]) =>
queryClient.setQueryData(key, data),
);
},
onSettled: () => queryClient.invalidateQueries({ queryKey: todoKeys.all }),
});
}
A reaction hook of mine updates four caches optimistically and snapshots only the feed. On failure the other three keep the wrong value, which onSettled overwrites so quickly that it's hard to spot. The snapshot has to cover every entry you touch, as getQueriesData does above.
Optimistic creates use a temp- id: block actions on that item and let onSettled replace it. In recent v5 versions (5.100 in my project), the third argument of onError is named onMutateResult, but its position hasn't changed, and older code that calls it context still works.
Zod checks rules and types, the server checks what only it knows
The TypeScript types come from the schema, so the rules and the types can't drift:
import { z } from 'zod';
export const signupSchema = z
.object({
displayName: z.string().trim().min(2, 'At least 2 characters'),
email: z.email('Enter a valid email'),
password: z.string().min(8, 'At least 8 characters'),
confirmPassword: z.string(),
})
.refine((v) => v.password === v.confirmPassword, {
error: 'Passwords do not match',
path: ['confirmPassword'],
});
export type SignupInput = z.input<typeof signupSchema>;
export type SignupValues = z.output<typeof signupSchema>;
export const SIGNUP_FIELDS = ['displayName', 'email', 'password'] as const;
The path in refine decides which field shows the error. Forget it and the error goes to root, where no input shows it. With trim or transform, input and output types differ: resolvers 5 passes both to useForm, while with resolvers 3 you write useForm<SignupValues> yourself. Zod 3 uses z.string().email() and message, which Zod 4 still accepts but marks deprecated.
Zod can't know whether an email is already registered. Only the server can. When the API says it is, the message goes right under the email field:
const queryClient = useQueryClient();
const form = useForm({
resolver: zodResolver(signupSchema),
defaultValues: { displayName: '', email: '', password: '', confirmPassword: '' },
});
const signup = useMutation({ mutationFn: createAccount });
const onSubmit = form.handleSubmit(async (values) => {
try {
await signup.mutateAsync(values);
await queryClient.invalidateQueries({ queryKey: sessionKeys.all });
} catch (error) {
const { fields, rest } = toFieldErrors(error, SIGNUP_FIELDS);
for (const [name, message] of Object.entries(fields)) {
form.setError(name as (typeof SIGNUP_FIELDS)[number], { type: 'server', message });
}
if (rest.length > 0 || Object.keys(fields).length === 0) {
form.setError('root.server', {
type: 'server',
message: rest[0] ?? 'Something went wrong. Please try again.',
});
}
}
});
mutateAsync keeps isSubmitting true for the whole request. It throws on failure, so the try is needed. A root.server error clears on the next submit, and a field error gets replaced the next time that field validates.
With setError, an unregistered field name renders nowhere. My current helper splits messages like "email must be an email" on the first word, which mostly works. The version I'd switch to maps only the names it knows and sends everything else to root:
type ApiFieldError = { field: string; message: string };
export function toFieldErrors<T extends string>(error: unknown, known: readonly T[]) {
const fields: Partial<Record<T, string>> = {};
const rest: string[] = [];
const issues = (error as { errors?: unknown } | null)?.errors;
if (!Array.isArray(issues)) return { fields, rest };
for (const { field, message } of issues as ApiFieldError[]) {
if ((known as readonly string[]).includes(field)) fields[field as T] ??= message;
else rest.push(message);
}
return { fields, rest };
}
// to-field-errors.test.ts
it('maps known fields and keeps the rest', () => {
const error = { errors: [
{ field: 'email', message: 'Email is already registered' },
{ field: 'plan', message: 'Plan is unavailable' },
] };
expect(toFieldErrors(error, ['email', 'displayName'])).toEqual({
fields: { email: 'Email is already registered' },
rest: ['Plan is unavailable'],
});
});
it.each([undefined, null, new Error('x'), { errors: 'nope' }])('ignores %p', (e) => {
expect(toFieldErrors(e, ['email'])).toEqual({ fields: {}, rest: [] });
});
I test pure functions like this with plain Jest outside React. My impression is that small it.each tables catch more bugs than component tests.
Dependent fields and a debounced search box
form.watch() at the top of a big form re-renders the whole form on every keystroke. I did that in quite a few forms and only noticed after installing react-scan (0.3.3) for a slow filter panel. Put useWatch in a small child component so only that child re-renders:
function AddressFields({ control }: { control: Control<AddressInput> }) {
const country = useWatch({ control, name: 'country' });
const cityText = useWatch({ control, name: 'cityText' });
const term = useDebouncedValue(cityText.trim(), 300);
const regions = useQuery({
...geoQueries.regions(country),
enabled: Boolean(country),
});
const cities = useQuery({
...geoQueries.cities(country, term),
enabled: Boolean(country) && term.length >= 2,
placeholderData: keepPreviousData,
});
return (
<>
<RegionSelect control={control} options={regions.data ?? []} />
<CityCombobox
control={control}
options={cities.data ?? []}
dimmed={cities.isPlaceholderData}
/>
</>
);
}
enabled turns the query into a dependent query. If you debounce the value rather than the fetch, the key changes only when typing stops. keepPreviousData keeps old results on screen while the new term loads. A disabled query with no data reports isPending: true, so spinners should check isFetching.
Debouncing an object built during render resets the timer on every render, since the reference is new each time. Build it from debounced primitives instead. When the country changes, clear the region with setValue('region', '') inside the country's onChange. Doing it in an effect that watches country means a reset with saved data also fires that effect and wipes the region you just loaded.
More posts
- 01
Deploying Next.js and NestJS to AWS EC2 with Docker Compose
How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.
- 02
How I store OAuth tokens for social media APIs in NestJS
OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.
- 03
llms.txt on my Next.js site, and now Lighthouse grades it
vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.