React Query is a powerful library for data fetching, caching, and synchronization in React applications. It simplifies the process of managing remote data in your React apps by handling aspects like caching, refetching, and background updates.
npm install @tanstack/react-query
In your root component (usually App.js or index.js), wrap your application with the QueryClientProvider from React Query:
import { QueryClient, QueryClientProvider } from'@tanstack/react-query'; const queryClient = newQueryClient(); functionApp() { return ( <QueryClientProvider client={queryClient}> <YourMainComponent /> </QueryClientProvider> ); } exportdefaultApp;
The useQuery hook is used to fetch data. Here’s an example of how to fetch data from an API:
import { useQuery } from '@tanstack/react-query';
function fetchProducts() {
return fetch('https://api.example.com/products').then((res) =>
res.json()
);
}
function ProductList() {
const { isLoading, error, data } = useQuery(['products'], fetchProducts);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
{data.map((product) => (
<div key={product.id}>
<h2>{product.name}</h2>
<p>{product.description}</p>
</div>
))}
</div>
);
}