State Management · Senior · Question 23 of 75
Why are query key factories recommended?
export const todoKeys = {
all: ["todos"] as const,
lists: () => [...todoKeys.all, "list"] as const,
list: (filters: Filters) => [...todoKeys.lists(), filters] as const,
detail: (id: number) => [...todoKeys.all, "detail", id] as const,
};- ✓Correct answer: Keys stay consistent and hierarchical, so invalidation by prefix is reliable
- 2TanStack Query requires keys to be declared in one object
- 3Factories make queries run in parallel
Explanation
Typos in hand-written keys silently break caching and invalidation. A factory gives one source of truth: invalidateQueries({ queryKey: todoKeys.lists() }) refreshes every list but not details.