
本文详解 TanStack React Query(v5+)在 Next.js 14 App Router 中因包版本不匹配、SSR/客户端混合使用导致的 hydrate is not exported 等导入失败问题,并提供兼容 v5 的正确服务端渲染(SSR)配置与 Provider 实现。
本文详解 tanstack react query(v5+)在 next.js 14 app router 中因包版本不匹配、ssr/客户端混合使用导致的 `hydrate is not exported` 等导入失败问题,并提供兼容 v5 的正确服务端渲染(ssr)配置与 provider 实现。
你遇到的错误——如 Attempted import error: 'hydrate' is not exported from '@tanstack/query-core'——根本原因并非代码写错,而是版本不兼容 + SSR 配置缺失。尤其当你使用 Next.js 14(App Router)时,React Query v5 已彻底移除 hydrate 函数,并改用全新的 HydrationBoundary 组件(注意:不是 Hydrate!),同时要求 @tanstack/query-core 与 @tanstack/react-query 版本严格对齐(必须同为 v5.x)。
✅ 正确配置步骤(Next.js 14 + React Query v5)
1. 确保版本统一且为 v5
运行以下命令清理并安装最新稳定版 v5:
npm uninstall @tanstack/react-query @tanstack/query-core npm install @tanstack/react-query@latest # 自动安装匹配的 @tanstack/query-core(v5.x)
⚠️ 警告:切勿混用 v4 和 v5。v4 的
Hydrate组件在 v5 中已被废弃;v5 使用HydrationBoundary,且其内部依赖的query-coreAPI 已重构。
Build React agent chat interfaces with assistant-ui下载使用 assistant-ui 构建具有可重用线程、运行时、消息组件和模型/提供者适配器的生产级 React 聊天界面。
2. 创建正确的 Client-Side Provider(TanstackProvider.tsx)
由于 Next.js App Router 的 layout.tsx 是服务端组件(Server Component),而 QueryClientProvider 必须在客户端渲染,因此需确保:
- Provider 文件标记
"use client" - 使用
useState初始化QueryClient(避免服务端重复创建) -
v5 中不再需要手动传递
dehydratedState到根 layout(除非你主动做 SSR 数据预取)
// src/app/_components/providers/TanstackProvider.tsx
"use client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { HydrationBoundary } from "@tanstack/react-query";
import { ReactNode, useState } from "react";
export default function TanstackProvider({ children }: { children: ReactNode }) {
const [queryClient] = useState(() => new QueryClient());
return (
<queryclientprovider client="{queryClient}">
{/* HydrationBoundary 用于包裹需要水合的子组件(如服务端预取的数据) */}
<hydrationboundary>
{children}
</hydrationboundary></queryclientprovider>
);
}
3. 在 layout.tsx 中正确使用(无需服务端传参)
layout.tsx 本身是 Server Component,但 TanstackProvider 是 Client Component,可直接嵌套使用:
page.tsx











