Exhaustive dependencies for query keys

· abundance's blog


Query keys should be seen like a dependency array to your query function: Every variable that is used inside the queryFn should be added to the query key. This makes sure that queries are cached independently and that queries are refetched automatically when the variables changes.

Rule Details #

Examples of incorrect code for this rule:

 1/* eslint "@tanstack/query/exhaustive-deps": "error" */
 2
 3useQuery({
 4  queryKey: ['todo'],
 5  queryFn: () => api.getTodo(todoId),
 6})
 7
 8const todoQueries = {
 9  detail: (id) => ({ queryKey: ['todo'], queryFn: () => api.getTodo(id) }),
10}

Examples of correct code for this rule:

1useQuery({
2  queryKey: ['todo', todoId],
3  queryFn: () => api.getTodo(todoId),
4})
5
6const todoQueries = {
7  detail: (id) => ({ queryKey: ['todo', id], queryFn: () => api.getTodo(id) }),
8}

When Not To Use It #

If you don't care about the rules of the query keys, then you will not need this rule.

Attributes #