Using React Query in Next.js
React Query is a powerful library for data fetching, caching, and state management in React applications. When combined with Next.js, it enables efficient server-side rendering (SSR), static site generation (SSG), and client-side fetching.
Why Use React Query?
- Simplifies data fetching logic
- Caching and background fetching out of the box
- Automatic refetching and synchronization
- Works with SSR and SSG in Next.js
Installation
To get started, install React Query and its devtools:
npm install @tanstack/react-query @tanstack/react-query-devtools
Setting Up React Query in Next.js
Wrap your application with QueryClientProvider
in _app.js
or _app.tsx
:
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
export default function MyApp({ Component, pageProps }) {
return (
<QueryClientProvider client={queryClient}>
<Component {...pageProps} />
</QueryClientProvider>
);
}
Fetching Data with React Query
You can use the useQuery
hook to fetch data in Next.js:
import { useQuery } from '@tanstack/react-query';
const fetchPosts = async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
return res.json();
};
export default function Posts() {
const { data, error, isLoading } = useQuery(['posts'], fetchPosts);
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error fetching posts</p>;
return (
<ul>
{data.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
Using React Query with SSR in Next.js
For server-side rendering (SSR), use dehydrate
and getServerSideProps
:
import { QueryClient, dehydrate, useQuery } from '@tanstack/react-query';
const fetchPosts = async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
return res.json();
};
export async function getServerSideProps() {
const queryClient = new QueryClient();
await queryClient.prefetchQuery(['posts'], fetchPosts);
return {
props: {
dehydratedState: dehydrate(queryClient),
},
};
}
export default function PostsPage() {
const { data } = useQuery(['posts'], fetchPosts);
return (
<ul>
{data.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
Using React Query with SSG in Next.js
For static site generation (SSG), use getStaticProps
:
export async function getStaticProps() {
const queryClient = new QueryClient();
await queryClient.prefetchQuery(['posts'], fetchPosts);
return {
props: {
dehydratedState: dehydrate(queryClient),
},
};
}
Enabling React Query DevTools
For debugging, you can enable React Query DevTools:
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
<QueryClientProvider client={queryClient}>
<Component {...pageProps} />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
Conclusion
React Query is a game-changer for handling data in Next.js applications. It simplifies data fetching, improves performance, and integrates well with SSR and SSG. By using React Query, you can optimize data fetching and caching in your Next.js projects efficiently.