react-2026
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseReact Stack Patterns
React技术栈模式
React has come a long way since its early days of simple component libraries. By late 2025, the React ecosystem is rich but complex, offering multiple ways to choose your stack for building apps. Modern React developers face choices at every layer of the stack - from build tools and frameworks to routers and other libraries. The official React documentation (now at react.dev) encourages using higher-level frameworks for new projects. In fact, Create React App (CRA) - once the go-to bootstrap tool - was deprecated in early 2025, signaling a shift in how we start React apps.
Instead of stitching together your own tooling from scratch, the recommendation is to either use a React framework (like Next.js or Remix) or, if you have special requirements, start from a modern build tool like Vite or Parcel. In this opinionated guide, we'll explore the 2025 React landscape: the toolchain and stack we suggest for mid-to-senior developers, covering build tools (Vite, Turbopack, Webpack), routing solutions (React Router vs. TanStack Router), popular frameworks (Next.js, Remix, etc.), key libraries for state and data management, and even how AI is influencing React development.
React从早期简单的组件库发展至今已经取得了长足的进步。到2025年末,React生态系统丰富但复杂,为应用构建提供了多种技术栈选择。现代React开发者在技术栈的每一层都面临选择——从构建工具、框架到路由和其他库。官方React文档(现托管于react.dev)鼓励新项目使用更高层级的框架。事实上,曾经的首选启动工具**Create React App (CRA)**已于2025年初被弃用,这标志着React应用启动方式的转变。
与其从头开始拼凑自己的工具链,建议你要么使用React框架(如Next.js或Remix),要么如果有特殊需求,从Vite或Parcel等现代构建工具开始。在这份带有主观倾向的指南中,我们将探索2025年的React生态:为中高级开发者推荐的工具链和技术栈,涵盖构建工具(Vite、Turbopack、Webpack)、路由解决方案(React Router vs. TanStack Router)、热门框架(Next.js、Remix等)、状态和数据管理的关键库,甚至AI如何影响React开发。
When to Use
适用场景
- Use this as a reference when choosing your React stack (framework, build tools, routing, state management)
- This is helpful when starting a new React project and evaluating modern ecosystem options
- 选择React技术栈(框架、构建工具、路由、状态管理)时,可将本指南作为参考
- 启动新React项目并评估现代生态选项时,本指南会有所帮助
Instructions
使用指南
- For full-stack apps needing SSR/SEO: use Next.js or Remix as the framework
- For SPAs, internal tools, and dashboards: use Vite + React Router or TanStack Router
- Use Vite as the build tool for any custom (non-framework) React setup
- Consider TanStack Router for type-safe routing in custom stacks; use framework-provided routing otherwise
- Use TanStack Query (React Query) for server state and Zustand or Redux for complex global state
- Use React 19 APIs (ref as prop, use(), Actions) where supported
- Embrace AI-assisted development tools but always validate generated code
- 对于需要SSR/SEO的全栈应用:使用Next.js或Remix作为框架
- 对于SPA、内部工具和仪表板:使用Vite + React Router或TanStack Router
- 任何自定义(非框架)React设置,都使用Vite作为构建工具
- 自定义技术栈中,若需要类型安全路由,可考虑TanStack Router;否则使用框架提供的路由
- 服务器状态使用TanStack Query(React Query),复杂全局状态使用Zustand或Redux
- 在支持的场景下使用React 19 API(ref作为prop、use()、Actions)
- 拥抱AI辅助开发工具,但始终要验证生成的代码
Details
详细内容
Target Audience: This guide is written for intermediate to senior React developers who know the basics and want to make informed choices about their stack in 2025.
目标受众: 本指南面向掌握React基础知识、希望在2025年为自己的技术栈做出明智选择的中高级React开发者。
Official Guidance and Evolving Best Practices
官方指导与不断演变的最佳实践
React's core team has updated its guidance in line with community trends. The new React docs emphasize "don't reinvent the wheel" when starting a project. Create React App served us well to quickly spin up React SPAs, but it struggled to scale to production needs (e.g. lacking built-in routing or SSR). With CRA now deprecated, developers are nudged either toward full-featured frameworks or assembling their own stack using lighter tools. The rule of thumb given by React core: if your app needs routing, you will benefit from a framework. Modern frameworks tightly integrate routing with data fetching, code-splitting, and more, so you don't end up writing a mini-framework yourself.
Why this shift? Over the last few years, React has introduced powerful features like hooks, concurrent rendering, and Server Components. But leveraging many of these in an optimal way often requires sophisticated tooling. Frameworks like Next.js have become the vehicle for React's newest capabilities (e.g. streaming SSR, server-side data loading, etc.). React Server Components (RSC) landed as a production-ready feature in Next.js 13's App Router, enabling a hybrid rendering model (server-driven UI with zero JS cost for server-rendered components). Early reports showed bundle size reductions over 20% when using RSC, since logic that runs on the server doesn't ship to the client. React 19 is also stabilizing Server Actions (invoked with a directive) which let you define form submissions or other mutations to run on the server - further blurring the line between front and back end.
'use server'That said, not every project needs a heavyweight framework. The React team acknowledges there are cases for going lean: small widgets, adding React to an existing site, or learning by building from scratch. If you choose the custom route, you can still follow React's updated "Build from Scratch" guides using modern tools like Vite or RSBuild.
React核心团队已根据社区趋势更新了指导方针。新的React文档强调,启动项目时*“不要重复造轮子”*。Create React App曾帮助我们快速搭建React SPA,但它在满足生产需求方面存在不足(例如缺乏内置路由或SSR)。随着CRA被弃用,开发者要么转向功能完整的框架,要么使用更轻量的工具组装自己的技术栈。React核心团队给出的经验法则是:如果你的应用需要路由,那么使用框架会让你受益。现代框架将路由与数据获取、代码分割等功能紧密集成,这样你就不必自己编写迷你框架。
为什么会有这种转变?在过去几年中,React引入了强大的功能,如Hooks、并发渲染和Server Components。但要以最优方式利用其中许多功能,往往需要复杂的工具。Next.js等框架已成为React最新功能的载体(如流式SSR、服务器端数据加载等)。React Server Components (RSC)作为生产就绪功能在Next.js 13的App Router中推出,实现了混合渲染模式(服务器驱动的UI,服务器渲染组件无需向客户端发送JS)。早期报告显示,使用RSC可将包大小减少20%以上,因为在服务器上运行的逻辑不会被打包到客户端。React 19还在稳定Server Actions(通过指令调用),它允许你定义在服务器上运行的表单提交或其他变更操作——进一步模糊了前后端的界限。
'use server'话虽如此,并非每个项目都需要重量级框架。React团队承认,有些场景适合轻量方案:小型组件、在现有站点中添加React功能,或者通过从头构建来学习。如果你选择自定义路线,仍然可以遵循React更新后的“从头构建”指南,使用Vite或RSBuild等现代工具。
Build Tools in 2025: Vite, Turbopack, and Beyond
2025年的构建工具:Vite、Turbopack及更多
The build toolchain is what transforms your React code (JSX, CSS, etc.) into something that runs in the browser. In 2025, the developer experience has greatly improved:
-
Vite has become the de facto choice for non-framework React projects. Vite provides a super-fast dev server (powered by ESBuild) and uses Rollup for production bundling. Its popularity has surged, and by 2025 its React integration is the second most widely used build setup after Next.js. The appeal: instant server start and near-instant module hot reloads. If you're migrating off CRA, the React team explicitly suggests Vite as a top choice.
-
Turbopack - the new Rust-based bundler introduced by Vercel - is an upcoming star positioned as the spiritual successor to Webpack, focused on incremental compilation for ultrafast reloads. It's integrated within Next.js, so if you use Next, you'll likely benefit from it. Outside of Next, Turbopack isn't yet a generic tool.
-
Webpack - the long-time workhorse - is still with us, but mostly in legacy mode. For new projects, you'd rarely choose Webpack directly in 2025 unless you have very specific needs. Webpack for legacy, Vite (or framework default) for greenfield.
-
Rspack / RSBuild - part of a new breed of Rust-powered bundlers. Rspack is a high-performance bundler largely compatible with Webpack's ecosystem. RSBuild is a zero-config build tool built on Rspack, offering an easy setup for frameworks including React.
In summary, our pick for most cases is Vite - it's quick to start, fast to run, and well-supported.
构建工具链负责将你的React代码(JSX、CSS等)转换为可在浏览器中运行的内容。到2025年,开发者体验已大幅提升:
-
Vite已成为非框架React项目的事实上的选择。Vite提供超快速的开发服务器(由ESBuild驱动),并使用Rollup进行生产打包。它的人气激增,到2025年,其React集成是仅次于Next.js的第二大最常用构建设置。它的吸引力在于:即时服务器启动和近乎即时的模块热重载。如果你要从CRA迁移,React团队明确建议Vite作为首选。
-
Turbopack——Vercel推出的基于Rust的新型打包器——是一颗冉冉升起的新星,定位为Webpack的精神继承者,专注于增量编译以实现超快重载。它已集成到Next.js中,因此如果你使用Next.js,很可能会从中受益。在Next.js之外,Turbopack还不是一个通用工具。
-
Webpack——长期的主力军——仍然存在,但主要处于遗留模式。在2025年,除非有非常特殊的需求,否则你很少会直接选择Webpack用于新项目。遗留项目用Webpack,新项目用Vite(或框架默认工具)。
-
Rspack / RSBuild——新一代基于Rust的打包器的一部分。Rspack是一个高性能打包器,与Webpack的生态系统高度兼容。RSBuild是基于Rspack构建的零配置构建工具,为包括React在内的框架提供简易设置。
总而言之,我们在大多数情况下的选择是Vite——它启动快、运行快,且支持良好。
Frameworks and Starting Points
框架与启动方案
Choosing a starting point for a React project in 2025 often means choosing a framework.
Next.js (Full-Stack React Framework): Next.js, maintained by Vercel, has become the go-to solution for production React apps. It provides out-of-the-box support for file-based routing, SSR, SSG, image optimization, API routes, and React Server Components. Next's strength is in its strong defaults and conventions. Our top recommendation for building a new React app when you want a complete solution.
Remix (and React Router v7): Remix emphasizes web fundamentals and progressive enhancement. Created by the React Router team, Remix introduced an integrated approach to routing + data loading + mutations. React Router v7 adopted many of Remix's patterns. A solid choice especially for apps where you want fine-grained control over server-vs-client work.
"No Framework" Custom Setup (Vite + library stack): If you decide a full framework is not needed, start with Vite and add pieces: e.g. React Router or TanStack Router for routing, React Query for data fetching. You might choose this for something like an internal tool where SSR/SEO are irrelevant.
Other Notables: Astro has gained attention for content sites (zero JS by default, mix frameworks). RedwoodJS offers an opinionated "React + GraphQL + Prisma + SSR" stack. Expo with the Expo Router brings React Native and web together.
Our opinionated advice: Match the tool to the job:
- Next.js for public-facing apps that need SSR, SEO, or server components
- Remix for apps that emphasize progressive enhancement and web fundamentals
- Vite + React Router/TanStack Router for SPAs, dashboards, internal tools, and any app where SSR isn't a requirement
Custom Vite SSR (without a meta-framework): If you need SSR but don't want a full framework, Vite has built-in SSR support. Tools like Vike (formerly vite-plugin-ssr) provide a thin layer on top of Vite for file-based routing with SSR, giving you framework-like DX while keeping full control.
typescript
// server.ts — minimal custom Vite SSR setup
import express from 'express'
import { createServer as createViteServer } from 'vite'
const app = express()
const vite = await createViteServer({ server: { middlewareMode: true } })
app.use(vite.middlewares)
app.use('*', async (req, res) => {
const template = await vite.transformIndexHtml(req.originalUrl, indexHtml)
const { render } = await vite.ssrLoadModule('/src/entry-server.tsx')
const appHtml = await render(req.originalUrl)
res.send(template.replace('<!--app-->', appHtml))
})This is a good fit when you need SSR for SEO or performance but your app's routing and data loading are simple enough that a framework adds more complexity than value.
Many successful React apps in 2025 run on Vite without a meta-framework. The key is choosing the right tool for your constraints, not defaulting to the most feature-rich option.
在2025年选择React项目的启动方案通常意味着选择一个框架。
Next.js(全栈React框架): 由Vercel维护的Next.js已成为生产级React应用的首选解决方案。它提供开箱即用的基于文件的路由、SSR、SSG、图片优化、API路由和React Server Components支持。Next.js的优势在于其强大的默认配置和约定。这是我们构建新React应用的首选推荐,如果你需要一个完整的解决方案。
Remix(及React Router v7): Remix强调Web基础和渐进式增强。由React Router团队创建的Remix引入了路由+数据加载+变更的集成方法。React Router v7采用了Remix的许多模式。对于希望精细控制服务器与客户端工作的应用来说,这是一个可靠的选择。
“无框架”自定义设置(Vite + 库技术栈): 如果你认为不需要完整框架,可以从Vite开始,然后添加所需组件:例如,React Router或TanStack Router用于路由,React Query用于数据获取。你可能会为内部工具这类SSR/SEO无关的场景选择这种方案。
其他值得注意的框架: Astro因内容站点(默认零JS,支持混合框架)受到关注。RedwoodJS提供了一个带有主观倾向的“React + GraphQL + Prisma + SSR”技术栈。Expo搭配Expo Router将React Native和Web整合在一起。
我们的主观建议: 按需选择工具:
- Next.js适用于需要SSR、SEO或服务器组件的面向公众的应用
- Remix适用于强调渐进式增强和Web基础的应用
- Vite + React Router/TanStack Router适用于SPA、仪表板、内部工具以及任何不需要SSR的应用
自定义Vite SSR(无元框架): 如果你需要SSR但不想使用完整框架,Vite内置了SSR支持。Vike(原vite-plugin-ssr)等工具在Vite之上提供了一个轻量级层,支持基于文件的路由和SSR,在保持完全控制权的同时提供类框架的开发体验。
typescript
// server.ts — 极简自定义Vite SSR设置
import express from 'express'
import { createServer as createViteServer } from 'vite'
const app = express()
const vite = await createViteServer({ server: { middlewareMode: true } })
app.use(vite.middlewares)
app.use('*', async (req, res) => {
const template = await vite.transformIndexHtml(req.originalUrl, indexHtml)
const { render } = await vite.ssrLoadModule('/src/entry-server.tsx')
const appHtml = await render(req.originalUrl)
res.send(template.replace('<!--app-->', appHtml))
})当你需要SSR来优化SEO或性能,但应用的路由和数据加载足够简单,框架带来的复杂度超过其价值时,这种方案非常合适。
2025年,许多成功的React应用在没有元框架的情况下运行在Vite上。关键是根据你的约束选择合适的工具,而不是默认选择功能最丰富的选项。
Routing Solutions: React Router vs. TanStack Router
路由解决方案:React Router vs. TanStack Router
Framework-provided Routing: If you use Next.js or Remix, routing is largely solved by the framework. These frameworks tie routing with data fetching closely, which avoids common pitfalls like loading waterfalls.
React Router: Battle-tested and widely used. React Router v6 introduced a simplified API with hooks and nested routes. By v6.4+, it added async data and suspense support. Still a top choice if you're not using a framework.
TanStack Router: A newer entrant with first-class TypeScript support, built-in data loaders with caching, and a rich API for search params. It's trying to give you the power of a Remix/Next router but decoupled from a specific framework.
The biggest differences: Type Safety and Developer Experience. TanStack Router is built "TS-first". React Router is more minimal. Both can do nested routes and data loading.
Our recommendation: For custom stacks, give TanStack Router a serious look for its modern feature set. React Router is still perfectly valid, especially if your team is already familiar with it.
jsx
import { createRootRoute, createRoute, createRouter, RouterProvider } from '@tanstack/react-router';
const rootRoute = createRootRoute();
const indexRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/',
component: () => <div>Hello, world!</div>,
});
const routeTree = rootRoute.addChildren([indexRoute]);
const router = createRouter({ routeTree });
export default function App() {
return <RouterProvider router={router} />;
}框架提供的路由: 如果你使用Next.js或Remix,路由问题基本由框架解决。这些框架将路由与数据获取紧密结合,避免了加载瀑布等常见陷阱。
React Router: 经过实战检验且被广泛使用。React Router v6引入了简化的API,包含Hooks和嵌套路由。到v6.4+,它添加了异步数据和Suspense支持。如果你不使用框架,它仍然是首选。
TanStack Router: 一个较新的选项,提供一流的TypeScript支持、内置的带缓存的数据加载器以及丰富的搜索参数API。它试图为你提供Remix/Next路由的强大功能,但与特定框架解耦。
最大差异: 类型安全性和开发者体验。TanStack Router是“TS优先”构建的。React Router更轻量化。两者都支持嵌套路由和数据加载。
我们的推荐: 对于自定义技术栈,认真考虑TanStack Router,因为它具有现代功能集。React Router仍然完全可用,尤其是如果你的团队已经熟悉它的话。
jsx
import { createRootRoute, createRoute, createRouter, RouterProvider } from '@tanstack/react-router';
const rootRoute = createRootRoute();
const indexRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/',
component: () => <div>Hello, world!</div>,
});
const routeTree = rootRoute.addChildren([indexRoute]);
const router = createRouter({ routeTree });
export default function App() {
return <RouterProvider router={router} />;
}State Management and Data Fetching Libraries
状态管理与数据获取库
Local and Global State with Hooks: For local state, and suffice. React's Context API works for lightweight global state but be careful — context updates re-render all consumers.
useStateuseReducerRedux (and modern Redux Toolkit): Very much alive in 2025, though concentrated in large applications. Redux Toolkit (RTK) significantly reduces boilerplate. When should you reach for Redux? If your app has very complex state transitions or you need features like undo/redo, caching, devtools.
Zustand, Jotai, and lightweight state libraries: For simpler global store needs. Zustand provides a minimalistic, hook-based global state store with no boilerplate.
TanStack Query: The leader for managing server state. Provides hooks like and to declaratively fetch and cache data.
useQueryuseMutationtsx
import { useQuery } from '@tanstack/react-query';
function TodoList() {
const { data: todos, error, isLoading } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
});
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <ul>{todos.map(t => <li key={t.id}>{t.title}</li>)}</ul>;
}React Query and friends remain relevant even in the age of RSC — they might be used more for mutations and real-time updates while initial loads shift to server-side.
Form State: React Hook Form has established itself as a great library. Coupled with Zod for schemas, you can validate inputs declaratively.
Key Libraries: MUI, Chakra UI, Radix UI, Headless UI for components. @tanstack/react-virtual for list virtualization. Vitest + React Testing Library for testing in Vite projects, Jest + React Testing Library for other setups, Cypress or Playwright for E2E.
使用Hooks管理本地和全局状态: 对于本地状态,和足够用。React的Context API适用于轻量级全局状态,但要注意——Context更新会重新渲染所有消费者。
useStateuseReducerRedux(及现代Redux Toolkit): 在2025年仍然非常活跃,但主要集中在大型应用中。**Redux Toolkit (RTK)**显著减少了样板代码。什么时候应该使用Redux? 如果你的应用有非常复杂的状态转换,或者你需要撤销/重做、缓存、开发者工具等功能。
Zustand、Jotai和轻量级状态库: 适用于更简单的全局存储需求。Zustand提供了一个极简的、基于Hook的全局状态存储,无样板代码。
TanStack Query: 管理服务器状态的领导者。提供和等Hooks,以声明式方式获取和缓存数据。
useQueryuseMutationtsx
import { useQuery } from '@tanstack/react-query';
function TodoList() {
const { data: todos, error, isLoading } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
});
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <ul>{todos.map(t => <li key={t.id}>{t.title}</li>)}</ul>;
}即使在RSC时代,React Query及相关库仍然重要——它们可能更多用于变更和实时更新,而初始加载则转移到服务器端。
表单状态: React Hook Form已成为一个优秀的库。搭配Zod用于 schema,你可以声明式地验证输入。
关键库: MUI、Chakra UI、Radix UI、Headless UI用于组件。@tanstack/react-virtual用于列表虚拟化。Vite项目使用Vitest + React Testing Library进行测试,其他设置使用Jest + React Testing Library,E2E测试使用Cypress或Playwright。
Testing with Vitest
使用Vitest进行测试
For Vite projects, Vitest is the natural testing companion — it shares Vite's config, transforms, and plugin pipeline, so there's no separate test bundler to configure or keep in sync.
typescript
// vite.config.ts — Vitest uses this directly
/// <reference types="vitest/config" />
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: './src/test/setup.ts',
css: true,
},
})typescript
// src/test/setup.ts
import '@testing-library/jest-dom/vitest'tsx
// src/components/Button.test.tsx
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Button } from './Button'
test('calls onClick when clicked', async () => {
const onClick = vi.fn()
render(<Button onClick={onClick}>Save</Button>)
await userEvent.click(screen.getByRole('button', { name: 'Save' }))
expect(onClick).toHaveBeenCalledOnce()
})Vitest gives you: instant watch mode (shared with Vite's transform cache), native ESM support, Jest-compatible API (, , , ), in-source testing, and built-in code coverage with or .
describeitexpectvi.fn()v8istanbul对于Vite项目,Vitest是自然的测试伙伴——它共享Vite的配置、转换和插件管道,因此无需配置或同步单独的测试打包器。
typescript
// vite.config.ts — Vitest直接使用此配置
/// <reference types="vitest/config" />
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: './src/test/setup.ts',
css: true,
},
})typescript
// src/test/setup.ts
import '@testing-library/jest-dom/vitest'tsx
// src/components/Button.test.tsx
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Button } from './Button'
test('calls onClick when clicked', async () => {
const onClick = vi.fn()
render(<Button onClick={onClick}>Save</Button>)
await userEvent.click(screen.getByRole('button', { name: 'Save' }))
expect(onClick).toHaveBeenCalledOnce()
})Vitest提供:即时监听模式(与Vite的转换缓存共享)、原生ESM支持、与Jest兼容的API(、、、)、源内测试,以及内置的或代码覆盖率。
describeitexpectvi.fn()v8istanbulReact 19 and Modern APIs
React 19与现代API
React 19 brings several significant API changes that simplify common patterns:
ref as a regular prop: No more — pass directly as a prop:
forwardRefreftsx
// React 19 — ref is just a prop
function Input({ ref, ...props }: InputProps & { ref?: React.Ref<HTMLInputElement> }) {
return <input ref={ref} {...props} />
}use()tsx
import { use } from 'react'
function UserPanel({ show }: { show: boolean }) {
if (!show) return null
const user = use(UserContext)
return <div>{user.name}</div>
}Actions and useActionState: Simplify form handling with server and client actions:
tsx
function ContactForm() {
const [state, formAction, isPending] = useActionState(submitContact, null)
return (
<form action={formAction}>
<input name="email" type="email" required />
<button disabled={isPending}>Submit</button>
{state?.error && <p>{state.error}</p>}
</form>
)
}useOptimistictsx
function TodoList({ todos }: { todos: Todo[] }) {
const [optimisticTodos, addOptimistic] = useOptimistic(todos)
async function addTodo(text: string) {
addOptimistic([...optimisticTodos, { id: 'temp', text, pending: true }])
await saveTodo(text)
}
return <ul>{optimisticTodos.map(t => <li key={t.id}>{t.text}</li>)}</ul>
}React Compiler: An opt-in compiler that auto-memoizes components and expressions, eliminating the need for manual , , and in most cases. For Vite projects, add it as a Babel plugin:
useMemouseCallbackReact.memotypescript
// vite.config.ts
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [
react({
babel: {
plugins: ['babel-plugin-react-compiler'],
},
}),
],
})Requires React 19. Can be adopted incrementally per-file with a directive.
'use memo'React 19带来了几项重要的API变更,简化了常见模式:
ref作为常规prop: 不再需要——直接将作为prop传递:
forwardRefreftsx
// React 19 — ref只是一个prop
function Input({ ref, ...props }: InputProps & { ref?: React.Ref<HTMLInputElement> }) {
return <input ref={ref} {...props} />
}use()tsx
import { use } from 'react'
function UserPanel({ show }: { show: boolean }) {
if (!show) return null
const user = use(UserContext)
return <div>{user.name}</div>
}Actions和useActionState: 简化服务器和客户端动作的表单处理:
tsx
function ContactForm() {
const [state, formAction, isPending] = useActionState(submitContact, null)
return (
<form action={formAction}>
<input name="email" type="email" required />
<button disabled={isPending}>Submit</button>
{state?.error && <p>{state.error}</p>}
</form>
)
}useOptimistictsx
function TodoList({ todos }: { todos: Todo[] }) {
const [optimisticTodos, addOptimistic] = useOptimistic(todos)
async function addTodo(text: string) {
addOptimistic([...optimisticTodos, { id: 'temp', text, pending: true }])
await saveTodo(text)
}
return <ul>{optimisticTodos.map(t => <li key={t.id}>{t.text}</li>)}</ul>
}React Compiler: 一个可选的编译器,自动对组件和表达式进行记忆化,在大多数情况下消除了手动、和的需求。对于Vite项目,将其作为Babel插件添加:
useMemouseCallbackReact.memotypescript
// vite.config.ts
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [
react({
babel: {
plugins: ['babel-plugin-react-compiler'],
},
}),
],
})需要React 19支持。可以通过指令按文件逐步采用。
'use memo'Vite-Specific Best Practices
Vite特定最佳实践
When using Vite + React (without a meta-framework), follow these essentials:
- Barrel file imports are the #1 bundle size issue — import directly from source files, not barrel files. Use
index.tsif you need ergonomic syntax.vite-plugin-barrel - Manual chunk splitting — split vendor code by stability (react, router, query, UI library) for better caching.
- Route-level code splitting — use for each route, wrapped in
React.lazy().<Suspense> - Dependency pre-bundling — add slow-to-resolve deps to for faster dev server.
optimizeDeps.include - Bundle analysis — run after every major dependency change.
npx vite-bundle-visualizer
See the vite-bundle-optimization skill for complete Vite configuration patterns.
当使用Vite + React(无元框架)时,请遵循以下要点:
- 桶文件导入是导致包体积过大的头号问题——直接从源文件导入,而不是从桶文件导入。如果需要符合人体工程学的语法,可以使用
index.ts。vite-plugin-barrel - 手动代码分割——按稳定性拆分供应商代码(react、router、query、UI库)以获得更好的缓存效果。
- 路由级代码分割——为每个路由使用,并包裹在
React.lazy()中。<Suspense> - 依赖预打包——将解析缓慢的依赖添加到中,以加快开发服务器启动速度。
optimizeDeps.include - 包分析——每次重大依赖变更后运行。
npx vite-bundle-visualizer
有关完整的Vite配置模式,请查看vite-bundle-optimization技能。
React + AI: The New Frontier of "Vibe Coding"
React + AI:“氛围编码”的新前沿
AI-Assisted Development: Tools like Copilot, ChatGPT, or Cursor can generate components, suggest hooks, and configure build tools. The term "vibe coding" describes a workflow where developers collaborate with AI assistants. Senior developers get more out of it because they know what to ask and how to verify the output.
Tips for "vibe coding" effectively:
- Use AI for boilerplate and configuration
- Generate component templates
- Leverage AI for tests and types
- Stay in control — always review AI-generated code
AI in React Apps (AI-powered UI): React developers are increasingly asked to build UIs that incorporate AI features. Key considerations include prompt management, streaming responses, error handling, and AI-specific UI elements. The Vercel AI SDK provides hooks like that abstract streaming and caching.
useChatOur take: Embrace AI as a tool in your React development workflow. Use your expertise to guide the AI: you define the architecture, let the AI fill in the boilerplate, then you refine the results.
AI辅助开发: Copilot、ChatGPT或Cursor等工具可以生成组件、建议Hooks并配置构建工具。**“氛围编码”**这个术语描述了开发者与AI助手协作的工作流。高级开发者能从中获得更多收益,因为他们知道该问什么以及如何验证输出。
有效进行“氛围编码”的技巧:
- 使用AI生成样板代码和配置
- 生成组件模板
- 利用AI生成测试和类型
- 保持控制权——始终审查AI生成的代码
React应用中的AI(AI驱动的UI): React开发者越来越多地被要求构建集成AI功能的UI。关键考虑因素包括提示管理、流式响应、错误处理以及AI特定的UI元素。Vercel AI SDK提供了等Hooks,抽象了流式传输和缓存。
useChat我们的观点: 将AI作为React开发工作流中的工具。利用你的专业知识引导AI:你定义架构,让AI填充样板代码,然后你优化结果。
Conclusion
结论
React in 2026 offers an abundance of choices:
- Build tool: Start with Vite for most cases (or Turbopack if inside Next.js).
- Framework or not: Lean towards using a React framework (Next.js being the frontrunner) for any sizeable app.
- Routing: If on Next/Remix, use what's built-in. If building your own stack, consider TanStack Router for type safety or React Router for reliability.
- State and data libraries: Use React Query for server data, Zustand or Redux for complex global state.
- Embrace new React features: Hooks are standard. Use React 19 APIs (, Actions,
use()). Understand Server Components. Try the React Compiler for auto-memoization.useOptimistic - Performance: Use for non-urgent updates, derived state over stored state,
useTransitionfor external subscriptions. See the react-render-optimization and react-data-fetching skills.useSyncExternalStore - AI in your workflow: Enhance productivity with AI coding assistants, but always validate output.
React is more powerful than ever. By choosing the right stack, you'll be well-equipped to build robust, scalable applications. Happy coding, and may your components re-render only when necessary!
2026年的React提供了丰富的选择:
- 构建工具: 大多数场景从Vite开始(如果在Next.js中则使用Turbopack)。
- 是否使用框架: 对于任何规模的应用,倾向于使用React框架(Next.js是首选)。
- 路由: 如果使用Next/Remix,使用内置路由;如果构建自己的技术栈,考虑类型安全的TanStack Router或可靠的React Router。
- 状态和数据库: 服务器数据使用React Query,复杂全局状态使用Zustand或Redux。
- 拥抱React新功能: Hooks已是标准。使用React 19 API(、Actions、
use())。了解Server Components。尝试React Compiler进行自动记忆化。useOptimistic - 性能: 使用处理非紧急更新,使用派生状态而非存储状态,使用
useTransition处理外部订阅。有关更多内容,请查看react-render-optimization和react-data-fetching技能。useSyncExternalStore - 工作流中的AI: 使用AI编码助手提高生产力,但始终要验证输出。
React比以往任何时候都更强大。通过选择正确的技术栈,你将能够构建健壮、可扩展的应用。祝你编码愉快,愿你的组件只在必要时重新渲染!