Step 1: Install and Configure
- In your existing React app (React 18+), run:
npm install @tanstack/react-query
- Create a QueryClient instance:
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
const queryClient = new QueryClient()
function App() {
return (
<QueryClientProvider client={queryClient}>
{/* Your app components */}
</QueryClientProvider>
)
}
- Test with a simple query fetching from JSONPlaceholder:
import { useQuery } from '@tanstack/react-query'
function Todos() {
const { data, isPending, error } = useQuery({
queryKey: ['todos'],
queryFn: () =>
fetch('https://jsonplaceholder.typicode.com/todos?_limit=5').then(
(res) => res.json(),
),
})
if (isPending) return <div>Loading...</div>
if (error) return <div>Error: {error.message}</div>
return (
<ul>
{data?.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
)
}
Add <Todos /> to your app.