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

quick-start.md

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