Categories
Next.js

React Query + Next.js 13

An example of a Next.js app that uses React Query for server-side data fetching and client-side caching:

import { GetServerSideProps } from 'next';
import { QueryClient, QueryClientProvider, useQuery } from 'react-query';
import { dehydrate } from 'react-query/hydration';

type Post = {
  id: number;
  title: string;
  body: string;
};

type PageProps = {
  posts: Post[];
};

const fetchPosts = async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts');
  const data = await response.json();
  return data;
};

const Posts = () => {
  const { data: posts } = useQuery<Post[]>('posts', fetchPosts);

  return (
    <div>
      {posts.map((post) => (
        <div key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.body}</p>
        </div>
      ))}
    </div>
  );
};

export const getServerSideProps: GetServerSideProps<PageProps> = async () => {
  const queryClient = new QueryClient();
  await queryClient.prefetchQuery('posts', fetchPosts);

  return {
    props: {
      posts: dehydrate(queryClient),
    },
  };
};

export default function Home(props: PageProps) {
  return (
    <QueryClientProvider client={new QueryClient()}>
      <Posts />
    </QueryClientProvider>
  );
}

This example demonstrates how to use the useQuery hook and QueryClient to fetch data from an API. We also use the dehydrate function to serialize the data in the query cache and pass it to the client for hydration.

In the getServerSideProps function, we prefetch the data using queryClient.prefetchQuery and pass the serialized data to the page component via the props object.

To render the component on the client, we use QueryClientProvider to provide a new QueryClient instance.

With this setup, the data will be fetched and cached on the server, and then hydrated on the client, allowing for smooth client-side rendering with minimal data fetching.

Note that this example uses the jsonplaceholder API for demonstration purposes only. In a real application, you would replace the API URL and data fetching function with your own API endpoint and data fetching logic.