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.
Examples of incorrect code for this rule:
/* eslint "@tanstack/query/exhaustive-deps": "error" */
useQuery({
queryKey: ['todo'],
queryFn: () => api.getTodo(todoId),
})
const todoQueries = {
detail: (id) => ({ queryKey: ['todo'], queryFn: () => api.getTodo(id) }),
}
/* eslint "@tanstack/query/exhaustive-deps": "error" */
useQuery({
queryKey: ['todo'],
queryFn: () => api.getTodo(todoId),
})
const todoQueries = {
detail: (id) => ({ queryKey: ['todo'], queryFn: () => api.getTodo(id) }),
}
Examples of correct code for this rule:
const Component = ({ todoId }) => {
const todos = useTodos()
useQuery({
queryKey: ['todo', todos, todoId],
queryFn: () => todos.getTodo(todoId),
})
}
const Component = ({ todoId }) => {
const todos = useTodos()
useQuery({
queryKey: ['todo', todos, todoId],
queryFn: () => todos.getTodo(todoId),
})
}
const todos = createTodos()
const todoQueries = {
detail: (id) => ({
queryKey: ['todo', id],
queryFn: () => todos.getTodo(id),
}),
}
const todos = createTodos()
const todoQueries = {
detail: (id) => ({
queryKey: ['todo', id],
queryFn: () => todos.getTodo(id),
}),
}
// with { allowlist: { variables: ["todos"] }}
const Component = ({ todoId }) => {
const todos = useTodos()
useQuery({
queryKey: ['todo', todoId],
queryFn: () => todos.getTodo(todoId),
})
}
// with { allowlist: { variables: ["todos"] }}
const Component = ({ todoId }) => {
const todos = useTodos()
useQuery({
queryKey: ['todo', todoId],
queryFn: () => todos.getTodo(todoId),
})
}
// with { allowlist: { types: ["TodosClient"] }}
class TodosClient { ... }
const Component = ({ todoId }) => {
const todos: TodosClient = new TodosClient()
useQuery({
queryKey: ['todo', todoId],
queryFn: () => todos.getTodo(todoId),
})
}
// with { allowlist: { types: ["TodosClient"] }}
class TodosClient { ... }
const Component = ({ todoId }) => {
const todos: TodosClient = new TodosClient()
useQuery({
queryKey: ['todo', todoId],
queryFn: () => todos.getTodo(todoId),
})
}
{
"@tanstack/query/exhaustive-deps": [
"error",
{
"allowlist": {
"variables": ["api", "config"],
"types": ["ApiClient", "Config"]
}
}
]
}
{
"@tanstack/query/exhaustive-deps": [
"error",
{
"allowlist": {
"variables": ["api", "config"],
"types": ["ApiClient", "Config"]
}
}
]
}
If you don't care about the rules of the query keys, then you will not need this rule.
