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

quick-start.md

81 lines1.7 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 { getTodos, postTodo } from '../my-api'
25​
26// Create a client
27const queryClient = new QueryClient()
28​
29function App() {
30 return (
31 // Provide the client to your App
32 <QueryClientProvider client={queryClient}>
33 <Todos />
34 </QueryClientProvider>
35 )
37​
38function Todos() {
39 // Access the client
40 const queryClient = useQueryClient()
41​
42 // Queries
43 const query = useQuery({ queryKey: ['todos'], queryFn: getTodos })
44​
45 // Mutations
46 const mutation = useMutation({
47 mutationFn: postTodo,
48 onSuccess: () => {
49 // Invalidate and refetch
50 queryClient.invalidateQueries({ queryKey: ['todos'] })
51 },
52 })
53​
54 return (
55 <div>
56 <ul>
57 {query.data?.map((todo) => (
58 <li key={todo.id}>{todo.title}</li>
59 ))}
60 </ul>
61​
62 <button
63 onClick={() => {
64 mutation.mutate({
65 id: Date.now(),
66 title: 'Do Laundry',
67 })
68 }}
69 >
70 Add Todo
71 </button>
72 </div>
73 )
75​
76render(<App />, document.getElementById('root'))
77```
78​
79[//]: # 'Example'
80​
81These 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.