TanStackQuery:React
lastmod 2025-05-25created 2023-11-279 edits
The React version of TanStack Query. (aka. react-query)
stale
APIs
useQuery
useQueryClient
useMutation
- (React) Handling asynchronous work with React Query (useEffect → useQuery → useMutation)
- (React Query) React Query useMutation basics
Example
import {
useQuery,
useMutation,
useQueryClient,
QueryClient,
QueryClientProvider,
} from '@tanstack/react-query'
import { getTodos, postTodo } from '../my-api'
// Create a client
const queryClient = new QueryClient()
function App() {
return (
// Provide the client to your App
<QueryClientProvider client={queryClient}>
<Todos />
</QueryClientProvider>
)
}
function Todos() {
// Access the client
const queryClient = useQueryClient()
// Queries
const query = useQuery({ queryKey: ['todos'], queryFn: getTodos })
// Mutations
const mutation = useMutation({
mutationFn: postTodo,
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries({ queryKey: ['todos'] })
},
})
return (
<div>
<ul>
{query.data?.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
<button
onClick={() => {
mutation.mutate({
id: Date.now(),
title: 'Do Laundry',
})
}}
>
Add Todo
</button>
</div>
)
}
render(<App />, document.getElementById('root'))
Troubleshooting
Query data cannot be undefined
Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ["summary"]
See also
- TanStack Query
- SWR (stale-while-revalidate)
Favorite site
- A look at React-Query
- Why KakaoPay frontend developers chose React Query | KakaoPay Tech Blog
- (React-Query) Getting the concepts of React-Query
- React Query vs SWR | MADTECH (React Query vs SWR)
- Build your own TanStack Query - Building React Query from scratch
Pages that link here