Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

quick-start.md

82 lines1.8 KB

1---
2id: quick-start
3title: Quick Start
4---
5​
6This code snippet very briefly illustrates the 3 core concepts of React Query:
7​
8- [Queries](./guides/queries.md)
9- [Mutations](./guides/mutations.md)
10- [Query Invalidation](./guides/query-invalidation.md)
11​
12[//]: # 'Example'
13​
14If you're looking for a fully functioning example, please have a look at our [simple StackBlitz example](./examples/simple)
15​
16```tsx
17import {
18 useQuery,
19 useMutation,
20 useQueryClient,
21 QueryClient,
22 QueryClientProvider,
23} from '@tanstack/react-query'
24import { createRoot } from 'react-dom/client'
25import { getTodos, postTodo } from '../my-api'
26​
27// Create a client
28const queryClient = new QueryClient()
29​
30function App() {
31 return (
32 // Provide the client to your App
33 <QueryClientProvider client={queryClient}>
34 <Todos />
35 </QueryClientProvider>
36 )
38​
39function Todos() {
40 // Access the client
41 const queryClient = useQueryClient()
42​
43 // Queries
44 const query = useQuery({ queryKey: ['todos'], queryFn: getTodos })
45​
46 // Mutations
47 const mutation = useMutation({
48 mutationFn: postTodo,
49 onSuccess: () => {
50 // Invalidate and refetch
51 queryClient.invalidateQueries({ queryKey: ['todos'] })
52 },
53 })
54​
55 return (
56 <div>
57 <ul>
58 {query.data?.map((todo) => (
59 <li key={todo.id}>{todo.title}</li>
60 ))}
61 </ul>
62​
63 <button
64 onClick={() => {
65 mutation.mutate({
66 id: Date.now(),
67 title: 'Do Laundry',
68 })
69 }}
70 >
71 Add Todo
72 </button>
73 </div>
74 )
76​
77createRoot(document.getElementById('root')).render(<App />)
78```
79​
80[//]: # 'Example'
81​
82These 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.