TanStack Query Patterns
Production-grade query patterns for Meridian's data layer. Covers stale-time tuning, optimistic mutations, infinite scrolling, and prefetch strategies that keep the dashboard snappy.
Stale-time by resource type
Session data refreshes aggressively; license keys cache longer. Tune staleTime per query key prefix.
const defaults = {
queries: {
staleTime: 30_000,
gcTime: 5 * 60_000,
},
};Optimistic mutation with rollback
Snapshot the cache before firing, revert on error. Works beautifully for toggle-style endpoints.
useMutation({
onMutate: async (newVal) => {
await queryClient.cancelQueries({ queryKey });
const prev = queryClient.getQueryData(queryKey);
queryClient.setQueryData(queryKey, newVal);
return { prev };
},
onError: (_err, _vars, ctx) => {
queryClient.setQueryData(queryKey, ctx.prev);
},
});Infinite scroll with cursor
Use useInfiniteQuery with a cursor-based API. Meridian's audit-log endpoint returns nextCursor for seamless pagination.
Prefetch on hover
Warm the cache before navigation. Attach onMouseEnter to list-item links and call queryClient.prefetchQuery.
Pro tip: Wrap your query client in a QueryClientProvider at the layout level so every route shares the same cache. Combine with React Router or Next.js App Router without extra plumbing.