Web / TanStack Interview Questions
How should you design queryKeys in TanStack Query and why do they matter?
The queryKey is a serialisable array uniquely identifying a cached query. TanStack Query uses it to look up the cache, trigger refetches when it changes, and scope invalidations. Organise keys from most-general to most-specific.
// Hierarchical â enables partial-match invalidation const allUsers = ["users"] const userById = ["users",{id:42}] const userPosts = ["users",{id:42},"posts"] // Invalidate ALL user-related queries at once queryClient.invalidateQueries({ queryKey:["users"] }) // Key-factory pattern â single source of truth, TypeScript catches typos export const userKeys = { all: () => ["users"] as const, detail: (id:number) => ["users",{id}] as const, posts: (id:number) => ["users",{id},"posts"] as const, } const { data } = useQuery({ queryKey: userKeys.detail(userId.value), queryFn: ()=>fetchUser(userId.value), })
More Related questions...