QueryKey design là nền tảng của cache architecture.
Rules:
- Include ALL dependencies — bất cứ biến nào dùng trong queryFn phải có trong key:
['todos', userId, { status, page, sort }]. - Dùng array, không dùng string thuần — array cho phép fuzzy matching khi invalidate.
- Hierarchy từ general đến specific:
['todos']→['todos', todoId]→['todos', todoId, 'comments']
Factory pattern (best practice): const todoKeys = { all: ['todos'] as const, lists: () => [...todoKeys.all, 'list'] as const, list: (filters) => [...todoKeys.lists(), filters] as const, detail: (id) => [...todoKeys.all, 'detail', id] as const } — dùng: useQuery({ queryKey: todoKeys.detail(id) }), invalidate: queryClient.invalidateQueries({ queryKey: todoKeys.lists() }).
Fuzzy matching rules: invalidateQueries({ queryKey: ['todos'] }) invalidates tất cả keys bắt đầu bằng 'todos' — cả ['todos', 1] lẫn ['todos', { status: 'active' }].
Serialization: React Query serialize key thành stable string cho cache lookup — objects được serialized theo key order.