React Query는 서버에서 데이터를 prefetching하여 queryClient에 전달하는 두 가지 방법을 지원합니다.
initialData
로 전달하기The exact implementation of these mechanisms may vary from platform to platform, but we recommend starting with Next.js which supports 2 forms of pre-rendering:
React Query supports both of these forms of pre-rendering regardless of what platform you may be using.
"Note: For notes about how to integrate with the new
/app
-folder in Next.js, see further down in this guide."
Together with Next.js's getStaticProps
or getServerSideProps
, you can pass the data you fetch in either method to useQuery
's' initialData
option. From React Query's perspective, these integrate in the same way, getStaticProps
is shown below:
export async function getStaticProps() {
const posts = await getPosts()
return { props: { posts } }
}
function Posts(props) {
const { data } = useQuery({
queryKey: ['posts'],
queryFn: getPosts,
initialData: props.posts,
})
// ...
}
The setup is minimal and this can be a quick solution for some cases, but there are a few tradeoffs to consider when compared to the full approach:
useQuery
in a component deeper down in the tree you need to pass the initialData
down to that pointuseQuery
with the same query in multiple locations, you need to pass initialData
to all of themdataUpdatedAt
and determining if the query needs refetching is based on when the page loaded insteadReact Query supports prefetching multiple queries on the server in Next.js and then dehydrating those queries to the queryClient. This means the server can prerender markup that is immediately available on page load and as soon as JS is available, React Query can upgrade or hydrate those queries with the full functionality of the library. This includes refetching those queries on the client if they have become stale since the time they were rendered on the server.
To support caching queries on the server and set up hydration:
QueryClient
instance inside of your app, and on an instance ref (or in React state). This ensures that data is not shared between different users and requests, while still only creating the QueryClient once per component lifecycle.<QueryClientProvider>
and pass it the client instance<Hydrate>
and pass it the dehydratedState
prop from pageProps
// _app.jsx
import {
Hydrate,
QueryClient,
QueryClientProvider,
} from '@tanstack/react-query'
export default function MyApp({ Component, pageProps }) {
const [queryClient] = React.useState(() => new QueryClient())
return (
<QueryClientProvider client={queryClient}>
<Hydrate state={pageProps.dehydratedState}>
<Component {...pageProps} />
</Hydrate>
</QueryClientProvider>
)
}
Reference