질문:
Is there any way to react query in Next 14 or later?
HydrationBoundary state={dehydrate(queryClient)}>
Is there a way to use this globally ?
Here is an example for version 13
export default function MyApp({ Component, pageProps }) {
const [queryClient] = React.useState(() => new QueryClient())
return (
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={pageProps.dehydratedState}>
<Component {...pageProps} />
</HydrationBoundary>
</QueryClientProvider>
)
}
이하 번역본:
혹시 넥스트 14버전 이상에서 리엑트쿼리
HydrationBoundary state={dehydrate(queryClient)}>
이것을 전역으로 사용하는 방법이 있는가요 ??
이하 13버전 예제
export default function MyApp({ Component, pageProps }) {
const [queryClient] = React.useState(() => new QueryClient())
return (
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={pageProps.dehydratedState}>
<Component {…pageProps} />
</HydrationBoundary>
</QueryClientProvider>
)
}
답:
Yes, you can still use React Query in Next.js 14 (or later), though some best practices have evolved, especially with App Router introduced in Next.js 13. Below is a revised way to manage hydration and state globally with HydrationBoundaryusing React Query. This setup will be compatible with the new App Router structure while preserving server-side rendering (SSR) and client-side hydration.
예, Next.js 14(또는 그 이후 버전)에서도 여전히 React Query를 사용할 수 있지만, 특히 Next.js 13에 도입된 앱 라우터와 함께 일부 모범 사례가 발전했습니다. 아래는 React Query를 사용하여 HydrationBoundary로 전역적으로 수화 및 상태를 관리하는 수정된 방법입니다. 이 설정은 서버 측 렌더링(SSR)과 클라이언트 측 하이드레이션을 유지하면서 새로운 App Router 구조와 호환됩니다.
Steps to Set It Up Globally
- Install React Query dependencies: React 쿼리 종속성을 설치합니다:
npm install @tanstack/react-query
npm install @tanstack/react-query-devtools
2. Global Query Provider with HydrationBoundary for App Router
For applications using the App Router (which became stable in Next.js 13), you'll want to wrap your entire app with the QueryClientProvider and HydrationBoundary components. This is how it can be structured using the new layout.jsor RootLayout:
앱 라우터용 HydrationBoundary가 포함된 글로벌 쿼리 공급자
앱 라우터(Next.js 13에서 안정화됨)를 사용하는 애플리케이션의 경우 전체 앱을 QueryClientProvider 및 HydrationBoundary 컴포넌트로 래핑하고 싶을 것입니다. 새로운 layout.js 또는 RootLayout을 사용하여 이렇게 구조화할 수 있습니다:
Example: Global Query Setup in layout.js (Next.js 14)
예시: layout.js의 전역 쿼리 설정(Next.js 14)
// app/layout.js (or app/layout.tsx if using TypeScript)
"use client";
import { ReactNode, useState } from "react";
import { HydrationBoundary, QueryClient, QueryClientProvider, DehydratedState, dehydrate } from "@tanstack/react-query";
// Create a Query Provider component for reuse
export default function RootLayout({
children,
dehydratedState,
}: {
children: ReactNode;
dehydratedState: DehydratedState;
}) {
const [queryClient] = useState(() => new QueryClient());
return (
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={dehydratedState}>
{children}
</HydrationBoundary>
</QueryClientProvider>
);
}
3. Usage with page.js / layout.js
In this new setup, each individual route or page component can receive the dehydratedState from SSR or static props and pass it to the global HydrationBoundary via the layout.js.
If you're fetching data from the server side, you can do something like this:
page.js / layout.js와 함께 사용
이 새로운 설정에서 각 개별 경로 또는 페이지 컴포넌트는 SSR 또는 정적 프롭에서 dehydratedState를 수신하여 layout.js를 통해 전역 HydrationBoundary로 전달할 수 있습니다.
서버 측에서 데이터를 가져오는 경우 다음과 같이 할 수 있습니다:
Example: Fetch Data with React Query on the Server
예시: 서버에서 React 쿼리를 사용하여 데이터 가져오기
// app/page.js (or any route component)
"use client";
import { useQuery } from "@tanstack/react-query";
async function fetchData() {
const res = await fetch("https://api.example.com/data");
return res.json();
}
export default function HomePage() {
const { data, isLoading, error } = useQuery(["myData"], fetchData);
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <div>Data: {JSON.stringify(data)}</div>;
}
4. SSR with generateStaticParams or fetchServerSideData
If you need to use SSR or SSG, you can fetch data on the server side and dehydrate the React Query state. Here’s how to do that:
generateStaticParams 또는 fetchServerSideData를 사용한 SSR
SSR 또는 SSG를 사용해야 하는 경우 서버 측에서 데이터를 가져와서 React 쿼리 상태를 탈수시킬 수 있습니다. 그 방법은 다음과 같습니다:
Example: Hydrate React Query State on Server Side
예시: 서버 측에서 리액트 쿼리 상태 하이드레이트하기
// app/layout.js or page.js (server side)
import { dehydrate, QueryClient } from "@tanstack/react-query";
import RootLayout from "./layout";
export async function generateStaticParams() {
const queryClient = new QueryClient();
await queryClient.prefetchQuery(["myData"], fetchData);
const dehydratedState = dehydrate(queryClient);
return {
props: {
dehydratedState,
},
};
}
Summary
With Next.js 13+ and 14, you can continue using React Query globally by following these patterns:
- Use QueryClientProvider and HydrationBoundary in the root layout (layout.js).
- Ensure you pass the dehydratedState from server-side fetching to HydrationBoundary.
- For server-side fetching, use generateStaticParams or getServerSideProps depending on your needs.
This setup works seamlessly with Next.js's new App Router, ensuring proper SSR and hydration while managing React Query globally.
요약
Next.js 13+ 및 14에서는 다음 패턴을 따라 React Query를 전역적으로 계속 사용할 수 있습니다:
루트 레이아웃(layout.js)에서 QueryClientProvider와 HydrationBoundary를 사용합니다.
서버 측 불러오기에서 HydrationBoundary로 dehydratedState를 전달해야 합니다.
서버 측 가져오기의 경우 필요에 따라 generateStaticParams 또는 getServerSideProps를 사용합니다.
이 설정은 Next.js의 새로운 앱 라우터와 원활하게 작동하여 React 쿼리를 전 세계적으로 관리하면서 적절한 SSR 및 하이드레이션을 보장합니다.