Using the initialData pattern
The initialData pattern is an option you can set in your useQuery hook. With this option, you can feed useQuery with the data that it will use to initialize a specific query.
This is the process of how to leverage the best of your server-side framework and React Query with the initialData option:
- The first thing you do is prefetch your data on the server side and send it to your component.
- Inside your component, you render your query using the
useQueryhook. - Inside this hook, you add the
initialDataoption and pass the data you prefetched on the server to it.
Let’s now see how to use this pattern in Next.js.
Applying the initialData pattern in Next.js
In the following snippet, we will fetch some data on the server using Next.js getServerSideProps and then leverage the initialData pattern to feed the data to React Query:
import axios from "axios";
import { useQuery } from "@tanstack/react-query"...