[TanStakQuery] SSR & Next.js

Jeris·2023년 5월 22일
0

React Query는 서버에서 데이터를 prefetching하여 queryClient에 전달하는 두 가지 방법을 지원합니다.

  • 데이터를 직접 prefetch하고 initialData로 전달하기
    • 간단한 경우 빠르게 설정할 수 있습니다
    • 몇 가지 주의 사항이 있습니다
  • 서버에서 쿼리를 prefetch하고 캐시를 dehydrate한 후 클라이언트에서 다시 rehydrate해야 합니다.
    • 약간 더 많은 사전 설정이 필요합니다

Using Next.js

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:

  • Static Generation (SSG)
  • Server-side Rendering (SSR)

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."

Using initialData

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:

  • If you are calling useQuery in a component deeper down in the tree you need to pass the initialData down to that point
  • If you are calling useQuery with the same query in multiple locations, you need to pass initialData to all of them
  • There is no way to know at what time the query was fetched on the server, so dataUpdatedAt and determining if the query needs refetching is based on when the page loaded instead

Using Hydration

React 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:

  • Create a new 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.
  • Wrap your app component with <QueryClientProvider> and pass it the client instance
  • Wrap your app component with <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

profile
job's done

0개의 댓글