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,
};

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.

Further reading

Problem with a question

State Management · Senior · question 23

Test yourself

Take the State Management · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz