Skip to content

Instantly share code, notes, and snippets.

@DarkAng3L
Created February 2, 2026 13:15
Show Gist options
  • Select an option

  • Save DarkAng3L/4479c8ad39fa31035e40e5ba1464dda4 to your computer and use it in GitHub Desktop.

Select an option

Save DarkAng3L/4479c8ad39fa31035e40e5ba1464dda4 to your computer and use it in GitHub Desktop.
react-query factory example with queryOptions()
import { useQuery, queryOptions, QueryClient } from '@tanstack/react-query'
type Todo = {
id: number
}
declare function fetchTodos(filters?: string): Promise<Array<Todo>>
declare function fetchTodo(id: number): Promise<Array<Todo>>
const queryClient = new QueryClient()
const todoKeys = {
all: ['todos'],
filter: (filters: string) => [...todoKeys.all, 'filter', filters],
detail: (id: number) => [...todoKeys.all, 'detail', id],
} as const
export const todoQueries = {
all: () =>
queryOptions({
queryKey: todoKeys.all,
queryFn: () => fetchTodos(),
}),
filter: (filters: string) =>
queryOptions({
queryKey: todoKeys.filter(filters),
queryFn: () => fetchTodos(filters),
}),
detail: (id: number) =>
queryOptions({
queryKey: todoKeys.detail(id),
queryFn: () => fetchTodo(id),
staleTime: 5000,
}),
}
const { data: todos } = useQuery(todoQueries.all())
const { data: firstTodo } = useQuery(todoQueries.detail(1))
const allTodoKeys = queryClient.getQueryData(todoQueries.all().queryKey) // allTodoKeys is same as todoKeys.all
// ^?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment