QueryKey là nền của kiến trúc cache. Ba nguyên tắc: đưa MỌI dependency dùng trong queryFn vào key (['todos', userId, { status, page, sort }]); dùng array chứ đừng dùng string thuần, vì array mới invalidate fuzzy được; xếp từ tổng quát đến cụ thể (['todos'] → ['todos', todoId] → ['todos', todoId, 'comments']).
Factory pattern là cách tổ chức key được khuyến nghị:
ts
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,
}
useQuery({ queryKey: todoKeys.detail(id), queryFn: () => fetchTodo(id) })
queryClient.invalidateQueries({ queryKey: todoKeys.lists() })- Fuzzy matching:
invalidateQueries({ queryKey: ['todos'] })invalidate mọi key bắt đầu bằng'todos'— cả['todos', 1]lẫn['todos', { status: 'active' }]. - React Query serialize key thành string ổn định để tra cache; object được serialize theo thứ tự key.