Integrating React Query with Next.js for data fetching provides a powerful combination for managing server state in your application. Here's how you can set it up and use it effectively:
Install React Query:
npm install @tanstack/react-query
Create a QueryClient and wrap your application with QueryClientProvider in _app.js or _app.tsx:
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useState } from 'react';
function MyApp({ Component, pageProps }) {
const [queryClient] = useState(() => new QueryClient());
return (
<QueryClientProvider client={queryClient}>
<Component {...pageProps} />
</QueryClientProvider>
);
}
export default MyApp;
For client-side data fetching, use the useQuery hook:
import { useQuery } from '@tanstack/react-query';
function ExampleComponent() {
const { data, isLoading, error } = useQuery(['uniqueKey'], async () => {
const response = await fetch('/api/data');
return response.json();
});
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>{JSON.stringify(data)}</div>;
}
For SSR, use dehydrate and Hydrate:
import { dehydrate, QueryClient, useQuery } from '@tanstack/react-query';
import { Hydrate } from '@tanstack/react-query/hydration';
export async function getServerSideProps() {
const queryClient = new QueryClient();
await queryClient.prefetchQuery(['key'], async () => {
const res = await fetch('https://api.example.com/data');
return res.json();
});
return {
props: {
dehydratedState: dehydrate(queryClient),
},
};
}
function Page({ dehydratedState }) {
return (
<Hydrate state={dehydratedState}>
<ExampleComponent />
</Hydrate>
);
}
export default Page;
By leveraging React Query in your Next.js application, you can significantly simplify data fetching logic, improve performance, and enhance the overall developer experience
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our ReactJS Expertise.