This code snippet very briefly illustrates the 3 core concepts of React Query:
If you're looking for a fully functioning example, please have a look at our simple StackBlitz example
1import {
2 useQuery,
3 useMutation,
4 useQueryClient,
5 QueryClient,
6 QueryClientProvider,
7} from '@tanstack/react-query'
8import { getTodos, postTodo } from '../my-api'
9
10// Create a client
11const queryClient = new QueryClient()
12
13function App() {
14 return (
15 // Provide the client to your App
16 <QueryClientProvider client={queryClient}>
17 <Todos />
18 </QueryClientProvider>
19 )
20}
21
22function Todos() {
23 // Access the client
24 const queryClient = useQueryClient()
25
26 // Queries
27 const query = useQuery({ queryKey: ['todos'], queryFn: getTodos })
28
29 // Mutations
30 const mutation = useMutation({
31 mutationFn: postTodo,
32 onSuccess: () => {
33 // Invalidate and refetch
34 queryClient.invalidateQueries({ queryKey: ['todos'] })
35 },
36 })
37
38 return (
39 <div>
40 <ul>{query.data?.map((todo) => <li key={todo.id}>{todo.title}</li>)}</ul>
41
42 <button
43 onClick={() => {
44 mutation.mutate({
45 id: Date.now(),
46 title: 'Do Laundry',
47 })
48 }}
49 >
50 Add Todo
51 </button>
52 </div>
53 )
54}
55
56render(<App />, document.getElementById('root'))
These three concepts make up most of the core functionality of React Query. The next sections of the documentation will go over each of these core concepts in great detail.