Trung BìnhState Management iconState Management

QueryKey trong React Query nên được thiết kế như thế nào?

QueryKey design là nền tảng của cache architecture.

Rules:

  1. Include ALL dependencies — bất cứ biến nào dùng trong queryFn phải có trong key: ['todos', userId, { status, page, sort }].
  2. Dùng array, không dùng string thuần — array cho phép fuzzy matching khi invalidate.
  3. 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.

Xem toàn bộ State Management cùng filter theo level & chủ đề con.

Mở danh sách State Management