Quick Start

This example very briefly illustrates the 3 core concepts of React Query:

  • Queries
  • Mutations
  • Query Invalidation
import { useQuery, useMutation, useQueryClient, QueryCache, QueryClient, QueryClientProvider } from 'react-query'
import { getTodos, postTodo } from '../my-api'
// Create a cache
const cache = new QueryCache()
// Create a client
const client = new QueryClient({ cache })
function App() {
return (
// Provide the client to your App
<QueryClientProvider client={client}>
<Todos />
</QueryClientProvider>
);
}
function Todos() {
// Access the client
const client = useQueryClient()
// Queries
const todosQuery = useQuery('todos', getTodos)
// Mutations
const [addTodo] = useMutation(postTodo, {
onSuccess: () => {
// Invalidate and refetch
client.invalidateQueries('todos')
},
})
return (
<div>
<ul>
{todosQuery.data.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
<button
onClick={() =>
addTodo({
id: Date.now(),
title: 'Do Laundry'
})
}
>
Add Todo
</button>
</div>
)
}
render(<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.

Was this page helpful?

Subscribe to our newsletter

The latest TanStack news, articles, and resources, sent to your inbox.

    I won't send you spam.

    Unsubscribe at any time.

    © 2020 Tanner Linsley. All rights reserved.