sajad torkamani

In a nutshell

React Query uses query keys to manage query caching. A query key should uniquely describe the data that is being fetched.

You’ll typically use a string as the query key to identify a collection of items (e.g., 'todos') or a serializable array like ['todos', todoId] to identify a particular resource item. You can also use array keys to identify a query that has filters applied (e.g., ['todos', {state: 'completed'}]).

Types of keys

String only key

String keys are converted to an array internally:

// A list of todos
useQuery('todos', ...) // queryKey === ['todos']
 
// Something else, whatever!
useQuery('somethingSpecial', ...) // queryKey === ['somethingSpecial']

Array keys

// An individual todo
useQuery(['todo', 5], ...)
// queryKey === ['todo', 5]
 
// An individual todo in a "preview" format
useQuery(['todo', 5, { preview: true }], ...)
// queryKey === ['todo', 5, { preview: true }]
 
// A list of todos that are "done"
useQuery(['todos', { type: 'done' }], ...)
// queryKey === ['todos', { type: 'done' }]

The order of keys in objects don’t matter. So the following queries will be considered equal:

useQuery(['todos', { status, page }], ...)
useQuery(['todos', { page, status }], ...)
useQuery(['todos', { page, status, other: undefined }], ...)

Sources / further reading

Leave a comment

Your email address will not be published. Required fields are marked *