react-best-practices by dedalus-erp-pas/foundation-skills
npx skills add https://github.com/dedalus-erp-pas/foundation-skills --skill react-best-practices构建现代 React 和 Next.js 应用程序的综合指南。涵盖性能优化、组件架构、shadcn/ui 模式、Motion 动画、可访问性以及 React 19+ 功能。
在以下情况下参考这些指南:
| 优先级 | 类别 | 影响 | 前缀 |
|---|---|---|---|
| 1 | 组件架构 | 关键 | arch- |
| 2 | 消除瀑布流 | 关键 | async- |
| 3 | 包大小优化 | 关键 |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
bundle- |
| 4 | 服务器组件与操作 | 高 | server- |
| 5 | shadcn/ui 模式 | 高 | shadcn- |
| 6 | 状态管理 | 中高 | state- |
| 7 | Motion 与动画 | 中 | motion- |
| 8 | 重新渲染优化 | 中 | rerender- |
| 9 | 可访问性 | 中 | a11y- |
| 10 | TypeScript 模式 | 中 | ts- |
arch-functional-components - 仅使用带钩子的函数式组件arch-composition-over-inheritance - 基于现有组件构建,不要继承arch-single-responsibility - 每个组件应做好一件事arch-presentational-container - 在有益时将 UI 与逻辑分离arch-colocation - 将相关文件放在一起(组件、样式、测试)arch-avoid-prop-drilling - 使用 Context 或组合来传递深层属性仅使用函数式组件
// 正确:带钩子的函数式组件
function UserProfile({ userId }: { userId: string }) {
const { data: user } = useUser(userId)
return <div>{user?.name}</div>
}
// 错误:类组件
class UserProfile extends React.Component { /* ... */ }
组合模式
// 正确:组合较小的组件
function Card({ children }: { children: React.ReactNode }) {
return <div className="rounded-lg border p-4">{children}</div>
}
function CardHeader({ children }: { children: React.ReactNode }) {
return <div className="font-semibold">{children}</div>
}
// 用法
<Card>
<CardHeader>标题</CardHeader>
<p>内容</p>
</Card>
避免属性透传
// 错误:通过多层传递属性
<App user={user}>
<Layout user={user}>
<Sidebar user={user}>
<UserMenu user={user} />
</Sidebar>
</Layout>
</App>
// 正确:使用 Context 共享状态
const UserContext = createContext<User | null>(null)
function App() {
const user = useCurrentUser()
return (
<UserContext.Provider value={user}>
<Layout>
<Sidebar>
<UserMenu />
</Sidebar>
</Layout>
</UserContext.Provider>
)
}
async-defer-await - 将 await 移到实际使用的地方async-parallel - 对独立操作使用 Promise.all()async-dependencies - 正确处理部分依赖关系async-api-routes - 在 API 路由中尽早启动 Promise,稍后等待async-suspense-boundaries - 使用 Suspense 流式传输内容瀑布流是头号性能杀手。每个顺序的 await 都会增加完整的网络延迟。
并行数据获取
// 错误:顺序瀑布流
async function Page() {
const user = await fetchUser()
const posts = await fetchPosts()
const comments = await fetchComments()
return <div>{/* 渲染 */}</div>
}
// 正确:并行获取
async function Page() {
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments()
])
return <div>{/* 渲染 */}</div>
}
战略性 Suspense 边界
// 在内容可用时流式传输
function Page() {
return (
<div>
<Header />
<Suspense fallback={<PostsSkeleton />}>
<Posts />
</Suspense>
<Suspense fallback={<CommentsSkeleton />}>
<Comments />
</Suspense>
</div>
)
}
bundle-barrel-imports - 直接导入,避免使用索引文件bundle-dynamic-imports - 对重型组件使用 next/dynamicbundle-defer-third-party - 在水合后加载分析/日志记录bundle-conditional - 仅在功能激活时加载模块bundle-preload - 在悬停/聚焦时预加载以提高感知速度避免索引文件导入
// 错误:导入整个库
import { Button } from '@/components'
import { formatDate } from '@/utils'
// 正确:直接导入支持摇树优化
import { Button } from '@/components/ui/button'
import { formatDate } from '@/utils/date'
动态导入
import dynamic from 'next/dynamic'
// 仅在需要时加载
const HeavyChart = dynamic(() => import('./HeavyChart'), {
loading: () => <ChartSkeleton />,
ssr: false
})
function Dashboard({ showChart }) {
return showChart ? <HeavyChart /> : null
}
server-default-server - 组件默认为服务器组件server-use-client-boundary - 仅在需要时添加 'use client'server-actions - 对变更操作使用服务器操作server-cache-react - 使用 React.cache() 进行请求级去重server-serialization - 最小化传递给客户端组件的数据默认服务器组件
// 服务器组件(默认)- 可以是异步的
async function ProductPage({ id }: { id: string }) {
const product = await db.product.findUnique({ where: { id } })
return <ProductDetails product={product} />
}
// 客户端组件 - 仅在需要交互性时使用
'use client'
function AddToCartButton({ productId }: { productId: string }) {
const [isPending, startTransition] = useTransition()
return (
<Button
onClick={() => startTransition(() => addToCart(productId))}
disabled={isPending}
>
加入购物车
</Button>
)
}
服务器操作
// actions.ts
'use server'
export async function createPost(formData: FormData) {
const title = formData.get('title') as string
const content = formData.get('content') as string
await db.post.create({ data: { title, content } })
revalidatePath('/posts')
}
// 组件用法
function CreatePostForm() {
return (
<form action={createPost}>
<Input name="title" placeholder="标题" />
<Textarea name="content" placeholder="内容" />
<Button type="submit">创建帖子</Button>
</form>
)
}
shadcn-composition - 基于现有的 shadcn/ui 原语构建shadcn-variants - 使用 class-variance-authority 处理组件变体shadcn-theme-integration - 使用 CSS 自定义属性进行主题化shadcn-accessibility - 利用 Radix 的内置可访问性shadcn-customization - 修改复制的组件,不要过度包装shadcn/ui 围绕以下原则构建:
# 根据需要添加组件
npx shadcn@latest add button
npx shadcn@latest add card
npx shadcn@latest add dialog
npx shadcn@latest add form
组合优先于创建
// 正确:基于现有原语构建
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
interface ProductCardProps {
product: Product
onSelect?: () => void
}
function ProductCard({ product, onSelect }: ProductCardProps) {
return (
<Card
className="cursor-pointer hover:shadow-md transition-shadow"
onClick={onSelect}
>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>{product.name}</CardTitle>
{product.isNew && <Badge>新</Badge>}
</div>
</CardHeader>
<CardContent>
<p className="text-muted-foreground">{product.description}</p>
<p className="text-lg font-bold mt-2">${product.price}</p>
</CardContent>
</Card>
)
}
使用 CVA 处理变体
import { cva, type VariantProps } from 'class-variance-authority'
import { cn } from '@/lib/utils'
const statusBadgeVariants = cva(
'inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold',
{
variants: {
status: {
pending: 'bg-yellow-100 text-yellow-800',
active: 'bg-green-100 text-green-800',
inactive: 'bg-gray-100 text-gray-800',
error: 'bg-red-100 text-red-800',
},
},
defaultVariants: {
status: 'pending',
},
}
)
interface StatusBadgeProps
extends React.HTMLAttributes<HTMLSpanElement>,
VariantProps<typeof statusBadgeVariants> {
label: string
}
function StatusBadge({ status, label, className, ...props }: StatusBadgeProps) {
return (
<span className={cn(statusBadgeVariants({ status }), className)} {...props}>
{label}
</span>
)
}
使用 React Hook Form + Zod 的表单
'use client'
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import * as z from 'zod'
import { Button } from '@/components/ui/button'
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
const formSchema = z.object({
email: z.string().email('无效的电子邮件地址'),
password: z.string().min(8, '密码必须至少 8 个字符'),
})
function LoginForm() {
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
email: '',
password: '',
},
})
function onSubmit(values: z.infer<typeof formSchema>) {
console.log(values)
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>电子邮件</FormLabel>
<FormControl>
<Input placeholder="you@example.com" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>密码</FormLabel>
<FormControl>
<Input type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full">登录</Button>
</form>
</Form>
)
}
对话框/模态框模式
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
function ConfirmDialog({
onConfirm,
title,
description
}: {
onConfirm: () => void
title: string
description: string
}) {
return (
<Dialog>
<DialogTrigger asChild>
<Button variant="destructive">删除</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline">取消</Button>
<Button variant="destructive" onClick={onConfirm}>
确认
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
使用 Tanstack Table 的数据表格
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import {
ColumnDef,
flexRender,
getCoreRowModel,
useReactTable,
} from '@tanstack/react-table'
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[]
data: TData[]
}
function DataTable<TData, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) {
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
})
return (
<div className="rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead key={header.id}>
{flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows.map((row) => (
<TableRow key={row.id}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</div>
)
}
state-local-first - 对本地状态使用 useState/useReducerstate-context-static - 对不常变化的数据使用 Contextstate-derived-compute - 计算派生值,不要存储它们state-url-state - 对可共享/可书签的状态使用 URLstate-server-state - 对服务器状态使用 SWR/TanStack Query避免派生状态
// 错误:存储派生状态
function ProductList({ products }) {
const [items, setItems] = useState(products)
const [count, setCount] = useState(products.length) // 派生的!
// 错误:count 可能与 items 不同步
}
// 正确:计算派生值
function ProductList({ products }) {
const [items, setItems] = useState(products)
const count = items.length // 始终保持同步
}
对过滤器/分页使用 URL 状态
'use client'
import { useSearchParams, useRouter } from 'next/navigation'
function ProductFilters() {
const searchParams = useSearchParams()
const router = useRouter()
const category = searchParams.get('category') || 'all'
function setCategory(newCategory: string) {
const params = new URLSearchParams(searchParams)
params.set('category', newCategory)
router.push(`?${params.toString()}`)
}
return (
<Select value={category} onValueChange={setCategory}>
{/* 选项 */}
</Select>
)
}
motion-purposeful - 动画应增强用户体验,而不是分散注意力motion-performance - 使用 transform/opacity,避免触发布局motion-reduced-motion - 尊重 prefers-reduced-motionmotion-layout-id - 对共享元素过渡使用 layoutIdmotion-exit-animations - 对退出动画使用 AnimatePresencemotion-variants - 定义可重用的动画状态npm install motion
Motion(前身为 Framer Motion)提供了增强用户体验的声明式动画。
基本动画
'use client'
import { motion } from 'motion/react'
function FadeInCard({ children }: { children: React.ReactNode }) {
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
className="rounded-lg border p-4"
>
{children}
</motion.div>
)
}
交互状态
function InteractiveButton({ children }: { children: React.ReactNode }) {
return (
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
transition={{ type: 'spring', stiffness: 400, damping: 17 }}
className="px-4 py-2 bg-primary text-primary-foreground rounded-md"
>
{children}
</motion.button>
)
}
使用 AnimatePresence 的退出动画
import { motion, AnimatePresence } from 'motion/react'
function NotificationList({ notifications }: { notifications: Notification[] }) {
return (
<AnimatePresence>
{notifications.map((notification) => (
<motion.div
key={notification.id}
initial={{ opacity: 0, x: 50 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -50 }}
transition={{ duration: 0.2 }}
>
<Notification data={notification} />
</motion.div>
))}
</AnimatePresence>
)
}
共享元素过渡
function ProductGrid({ products }: { products: Product[] }) {
const [selected, setSelected] = useState<Product | null>(null)
return (
<>
<div className="grid grid-cols-3 gap-4">
{products.map((product) => (
<motion.div
key={product.id}
layoutId={`product-${product.id}`}
onClick={() => setSelected(product)}
className="cursor-pointer"
>
<img src={product.image} alt={product.name} />
</motion.div>
))}
</div>
<AnimatePresence>
{selected && (
<motion.div
layoutId={`product-${selected.id}`}
className="fixed inset-0 flex items-center justify-center"
>
<ProductDetail product={selected} onClose={() => setSelected(null)} />
</motion.div>
)}
</AnimatePresence>
</>
)
}
可重用的变体
const fadeInUp = {
initial: { opacity: 0, y: 20 },
animate: { opacity: 1, y: 0 },
exit: { opacity: 0, y: -20 },
}
const staggerContainer = {
animate: {
transition: {
staggerChildren: 0.1,
},
},
}
function StaggeredList({ items }: { items: string[] }) {
return (
<motion.ul variants={staggerContainer} initial="initial" animate="animate">
{items.map((item, i) => (
<motion.li key={i} variants={fadeInUp}>
{item}
</motion.li>
))}
</motion.ul>
)
}
滚动触发的动画
import { motion, useInView } from 'motion/react'
import { useRef } from 'react'
function ScrollReveal({ children }: { children: React.ReactNode }) {
const ref = useRef(null)
const isInView = useInView(ref, { once: true, margin: '-100px' })
return (
<motion.div
ref={ref}
initial={{ opacity: 0, y: 50 }}
animate={isInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 50 }}
transition={{ duration: 0.5 }}
>
{children}
</motion.div>
)
}
尊重减少动画设置
import { motion, useReducedMotion } from 'motion/react'
function AccessibleAnimation({ children }: { children: React.ReactNode }) {
const shouldReduceMotion = useReducedMotion()
return (
<motion.div
initial={{ opacity: 0, y: shouldReduceMotion ? 0 : 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: shouldReduceMotion ? 0 : 0.3 }}
>
{children}
</motion.div>
)
}
transform 和 opacity 实现平滑的 60fps 动画willChange 属性useInView 懒加载动画width、height、top、leftrerender-memo - 将昂贵的工作提取到记忆化组件中rerender-usememo - 记忆化昂贵的计算rerender-usecallback - 稳定回调引用rerender-dependencies - 在 effect 中使用原始依赖项rerender-transitions - 对非紧急更新使用 startTransition对昂贵组件进行记忆化
import { memo } from 'react'
const ExpensiveList = memo(function ExpensiveList({
items
}: {
items: Item[]
}) {
return (
<ul>
{items.map(item => (
<li key={item.id}>{/* 昂贵的渲染 */}</li>
))}
</ul>
)
})
稳定的回调
function Parent() {
const [count, setCount] = useState(0)
// 稳定引用 - 不会导致子组件重新渲染
const handleClick = useCallback(() => {
setCount(c => c + 1)
}, [])
return <MemoizedChild onClick={handleClick} />
}
使用过渡进行非紧急更新
function SearchResults() {
const [query, setQuery] = useState('')
const [results, setResults] = useState([])
const [isPending, startTransition] = useTransition()
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
setQuery(e.target.value) // 紧急:立即更新输入
startTransition(() => {
setResults(filterResults(e.target.value)) // 非紧急:可以被中断
})
}
return (
<>
<Input value={query} onChange={handleChange} />
{isPending && <Spinner />}
<ResultsList results={results} />
</>
)
}
a11y-semantic-html - 使用正确的 HTML 元素a11y-keyboard-nav - 确保键盘可导航性a11y-aria-labels - 为屏幕阅读器添加描述性标签a11y-focus-management - 在模态框和动态内容中管理焦点a11y-color-contrast - 确保足够的颜色对比度语义化 HTML
// 错误:div 汤
<div onClick={handleClick}>点击我</div>
// 正确:语义化按钮
<button onClick={handleClick}>点击我</button>
模态框中的焦点管理
function Modal({ isOpen, onClose, children }) {
const closeButtonRef = useRef<HTMLButtonElement>(null)
useEffect(() => {
if (isOpen) {
closeButtonRef.current?.focus()
}
}, [isOpen])
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent>
{children}
<Button ref={closeButtonRef} onClick={onClose}>
关闭
</Button>
</DialogContent>
</Dialog>
)
}
跳过链接
function Layout({ children }) {
return (
<>
<a
href="#main-content"
className="sr-only focus:not-sr-only focus:absolute focus:top-4 focus:left-4"
>
跳转到主要内容
</a>
<Header />
<main id="main-content">{children}</main>
</>
)
}
ts-strict-mode - 启用严格的 TypeScript 配置ts-component-props - 定义明确的属性接口ts-generics - 对可重用组件使用泛型ts-discriminated-unions - 对状态机使用ts-infer-when-possible - 在明显时让 TypeScript 推断组件属性
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'default' | 'destructive' | 'outline'
size?: 'sm' | 'md' | 'lg'
isLoading?: boolean
}
function Button({
variant = 'default',
size = 'md',
isLoading,
children,
disabled,
...props
}: ButtonProps) {
return (
<button
disabled={disabled || isLoading}
{...props}
>
{isLoading ? <Spinner /> : children}
</button>
)
}
对状态使用可辨识联合
type AsyncState<T> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: Error }
function useAsync<T>(asyncFn: () => Promise<T>) {
const [state, setState] = useState<AsyncState<T>>({ status: 'idle' })
// TypeScript 根据状态知道确切形状
if (state.status === 'success') {
return state.data // TypeScript 知道 data 存在
}
}
泛型组件
interface SelectProps<T> {
options: T[]
value: T
onChange: (value: T) => void
getLabel: (option: T) => string
getValue: (option: T) => string
}
function Select<T>({ options, value, onChange, getLabel, getValue }: SelectProps<T>) {
return (
<select
value={getValue(value)}
onChange={(e) => {
const selected = options.find(o => getValue(o) === e.target.value)
if (selected) onChange(selected)
}}
>
{options.map((option) => (
<option key={getValue(option)} value={getValue(option)}>
{getLabel(option)}
</option>
))}
</select>
)
}
useActionState - 表单状态管理
'use client'
import { useActionState } from 'react'
function SubscribeForm() {
const [state, formAction, isPending] = useActionState(
async (prevState, formData) => {
const email = formData.get('email')
const result = await subscribe(email)
return result
},
null
)
return (
<form action={formAction}>
<Input name="email" type="email" />
<Button type="submit" disabled={isPending}>
{isPending ? '订阅中...' : '订阅'}
</Button>
{state?.error && <p className="text-red-500">{state.error}</p>}
</form>
)
}
useOptimistic - 乐观 UI 更新
'use client'
import { useOptimistic } from 'react'
function TodoList({ todos }: { todos: Todo[] }) {
const [optimisticTodos, addOptimisticTodo] = useOptimistic(
todos,
(state, newTodo: Todo) => [...state, newTodo]
)
async function addTodo(formData: FormData) {
const title = formData.get('title') as string
const newTodo = { id: crypto.randomUUID(), title, completed: false }
addOptimisticTodo(newTodo) // 立即在 UI 中显示
await createTodo(title) // 然后持久化到服务器
}
return (
<>
<form action={addTodo}>
<Input name="title" />
<Button type="submit">添加</Button>
</form>
<ul>
{optimisticTodos.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
</>
)
}
use - 异步资源读取
import { use, Suspense } from 'react'
async function fetchUser(id: string): Promise<User> {
const res = await fetch(`/api/users/${id}`)
return res.json()
}
function UserProfile({ userPromise }: { userPromise: Promise<User> }) {
const user = use(userPromise) // 在解析前暂停
return <div>{user.name}</div>
}
function Page({ userId }: { userId: string }) {
const userPromise = fetchUser(userId)
return (
<Suspense fallback={<UserSkeleton />}>
<UserProfile userPromise={userPromise} />
</Suspense>
)
}
src/
├── app/ # Next.js App Router
│ ├── layout.tsx
│ ├── page.tsx
│ └── (routes)/
├── components/
│ ├── ui/ # shadcn/ui 组件
│ │ ├── button.tsx
│ │ ├── card.tsx
│ │ └── ...
│ └── features/ # 特定功能组件
│ ├── auth/
│ └── dashboard/
├── hooks/ # 自定义钩子
├── lib/ # 工具函数
│ ├── utils.ts # cn() 辅助函数等
│ └── validations.ts # Zod 模式
├── actions/ # 服务器操作
└── types/ # TypeScript 类型
每周安装次数
94
仓库
GitHub 星标数
2
首次出现
2026年1月21日
安全审计
安装在
claude-code78
opencode76
github-copilot71
codex71
gemini-cli69
cursor64
Comprehensive guide for building modern React and Next.js applications. Covers performance optimization, component architecture, shadcn/ui patterns, Motion animations, accessibility, and React 19+ features.
Reference these guidelines when:
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Component Architecture | CRITICAL | arch- |
| 2 | Eliminating Waterfalls | CRITICAL | async- |
| 3 | Bundle Size Optimization | CRITICAL | bundle- |
| 4 | Server Components & Actions | HIGH | server- |
| 5 | shadcn/ui Patterns | HIGH | shadcn- |
| 6 | State Management | MEDIUM-HIGH | state- |
| 7 | Motion & Animations | MEDIUM | motion- |
| 8 | Re-render Optimization | MEDIUM | rerender- |
| 9 | Accessibility | MEDIUM | a11y- |
| 10 | TypeScript Patterns | MEDIUM | ts- |
arch-functional-components - Use functional components with hooks exclusivelyarch-composition-over-inheritance - Build on existing components, don't extendarch-single-responsibility - Each component should do one thing wellarch-presentational-container - Separate UI from logic when beneficialarch-colocation - Keep related files together (component, styles, tests)arch-avoid-prop-drilling - Use Context or composition for deep propsFunctional Components Only
// Correct: Functional component with hooks
function UserProfile({ userId }: { userId: string }) {
const { data: user } = useUser(userId)
return <div>{user?.name}</div>
}
// Incorrect: Class component
class UserProfile extends React.Component { /* ... */ }
Composition Pattern
// Correct: Compose smaller components
function Card({ children }: { children: React.ReactNode }) {
return <div className="rounded-lg border p-4">{children}</div>
}
function CardHeader({ children }: { children: React.ReactNode }) {
return <div className="font-semibold">{children}</div>
}
// Usage
<Card>
<CardHeader>Title</CardHeader>
<p>Content</p>
</Card>
Avoid Prop Drilling
// Incorrect: Passing props through many levels
<App user={user}>
<Layout user={user}>
<Sidebar user={user}>
<UserMenu user={user} />
</Sidebar>
</Layout>
</App>
// Correct: Use Context for shared state
const UserContext = createContext<User | null>(null)
function App() {
const user = useCurrentUser()
return (
<UserContext.Provider value={user}>
<Layout>
<Sidebar>
<UserMenu />
</Sidebar>
</Layout>
</UserContext.Provider>
)
}
async-defer-await - Move await into branches where actually usedasync-parallel - Use Promise.all() for independent operationsasync-dependencies - Handle partial dependencies correctlyasync-api-routes - Start promises early, await late in API routesasync-suspense-boundaries - Use Suspense to stream contentWaterfalls are the #1 performance killer. Each sequential await adds full network latency.
Parallel Data Fetching
// Incorrect: Sequential waterfalls
async function Page() {
const user = await fetchUser()
const posts = await fetchPosts()
const comments = await fetchComments()
return <div>{/* render */}</div>
}
// Correct: Parallel fetching
async function Page() {
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments()
])
return <div>{/* render */}</div>
}
Strategic Suspense Boundaries
// Stream content as it becomes available
function Page() {
return (
<div>
<Header />
<Suspense fallback={<PostsSkeleton />}>
<Posts />
</Suspense>
<Suspense fallback={<CommentsSkeleton />}>
<Comments />
</Suspense>
</div>
)
}
bundle-barrel-imports - Import directly, avoid barrel filesbundle-dynamic-imports - Use next/dynamic for heavy componentsbundle-defer-third-party - Load analytics/logging after hydrationbundle-conditional - Load modules only when feature is activatedbundle-preload - Preload on hover/focus for perceived speedAvoid Barrel File Imports
// Incorrect: Imports entire library
import { Button } from '@/components'
import { formatDate } from '@/utils'
// Correct: Direct imports enable tree-shaking
import { Button } from '@/components/ui/button'
import { formatDate } from '@/utils/date'
Dynamic Imports
import dynamic from 'next/dynamic'
// Load only when needed
const HeavyChart = dynamic(() => import('./HeavyChart'), {
loading: () => <ChartSkeleton />,
ssr: false
})
function Dashboard({ showChart }) {
return showChart ? <HeavyChart /> : null
}
server-default-server - Components are Server Components by defaultserver-use-client-boundary - Add 'use client' only when neededserver-actions - Use Server Actions for mutationsserver-cache-react - Use React.cache() for per-request deduplicationserver-serialization - Minimize data passed to client componentsServer Components by Default
// Server Component (default) - can be async
async function ProductPage({ id }: { id: string }) {
const product = await db.product.findUnique({ where: { id } })
return <ProductDetails product={product} />
}
// Client Component - only when needed for interactivity
'use client'
function AddToCartButton({ productId }: { productId: string }) {
const [isPending, startTransition] = useTransition()
return (
<Button
onClick={() => startTransition(() => addToCart(productId))}
disabled={isPending}
>
Add to Cart
</Button>
)
}
Server Actions
// actions.ts
'use server'
export async function createPost(formData: FormData) {
const title = formData.get('title') as string
const content = formData.get('content') as string
await db.post.create({ data: { title, content } })
revalidatePath('/posts')
}
// Component usage
function CreatePostForm() {
return (
<form action={createPost}>
<Input name="title" placeholder="Title" />
<Textarea name="content" placeholder="Content" />
<Button type="submit">Create Post</Button>
</form>
)
}
shadcn-composition - Build on existing shadcn/ui primitivesshadcn-variants - Use class-variance-authority for component variantsshadcn-theme-integration - Use CSS custom properties for themingshadcn-accessibility - Leverage built-in accessibility from Radixshadcn-customization - Modify copied components, don't wrap excessivelyshadcn/ui is built around:
# Add components as needed
npx shadcn@latest add button
npx shadcn@latest add card
npx shadcn@latest add dialog
npx shadcn@latest add form
Composition Over Creation
// Correct: Build on existing primitives
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
interface ProductCardProps {
product: Product
onSelect?: () => void
}
function ProductCard({ product, onSelect }: ProductCardProps) {
return (
<Card
className="cursor-pointer hover:shadow-md transition-shadow"
onClick={onSelect}
>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>{product.name}</CardTitle>
{product.isNew && <Badge>New</Badge>}
</div>
</CardHeader>
<CardContent>
<p className="text-muted-foreground">{product.description}</p>
<p className="text-lg font-bold mt-2">${product.price}</p>
</CardContent>
</Card>
)
}
Using Variants with CVA
import { cva, type VariantProps } from 'class-variance-authority'
import { cn } from '@/lib/utils'
const statusBadgeVariants = cva(
'inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold',
{
variants: {
status: {
pending: 'bg-yellow-100 text-yellow-800',
active: 'bg-green-100 text-green-800',
inactive: 'bg-gray-100 text-gray-800',
error: 'bg-red-100 text-red-800',
},
},
defaultVariants: {
status: 'pending',
},
}
)
interface StatusBadgeProps
extends React.HTMLAttributes<HTMLSpanElement>,
VariantProps<typeof statusBadgeVariants> {
label: string
}
function StatusBadge({ status, label, className, ...props }: StatusBadgeProps) {
return (
<span className={cn(statusBadgeVariants({ status }), className)} {...props}>
{label}
</span>
)
}
Forms with React Hook Form + Zod
'use client'
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import * as z from 'zod'
import { Button } from '@/components/ui/button'
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
const formSchema = z.object({
email: z.string().email('Invalid email address'),
password: z.string().min(8, 'Password must be at least 8 characters'),
})
function LoginForm() {
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
email: '',
password: '',
},
})
function onSubmit(values: z.infer<typeof formSchema>) {
console.log(values)
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input placeholder="you@example.com" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full">Sign In</Button>
</form>
</Form>
)
}
Dialog/Modal Pattern
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
function ConfirmDialog({
onConfirm,
title,
description
}: {
onConfirm: () => void
title: string
description: string
}) {
return (
<Dialog>
<DialogTrigger asChild>
<Button variant="destructive">Delete</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline">Cancel</Button>
<Button variant="destructive" onClick={onConfirm}>
Confirm
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
Data Table with Tanstack Table
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import {
ColumnDef,
flexRender,
getCoreRowModel,
useReactTable,
} from '@tanstack/react-table'
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[]
data: TData[]
}
function DataTable<TData, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) {
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
})
return (
<div className="rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead key={header.id}>
{flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows.map((row) => (
<TableRow key={row.id}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</div>
)
}
state-local-first - Use useState/useReducer for local statestate-context-static - Use Context for infrequently changing datastate-derived-compute - Compute derived values, don't store themstate-url-state - Use URL for shareable/bookmarkable statestate-server-state - Use SWR/TanStack Query for server stateAvoid Derived State
// Incorrect: Storing derived state
function ProductList({ products }) {
const [items, setItems] = useState(products)
const [count, setCount] = useState(products.length) // Derived!
// Bug: count can get out of sync with items
}
// Correct: Compute derived values
function ProductList({ products }) {
const [items, setItems] = useState(products)
const count = items.length // Always in sync
}
URL State for Filters/Pagination
'use client'
import { useSearchParams, useRouter } from 'next/navigation'
function ProductFilters() {
const searchParams = useSearchParams()
const router = useRouter()
const category = searchParams.get('category') || 'all'
function setCategory(newCategory: string) {
const params = new URLSearchParams(searchParams)
params.set('category', newCategory)
router.push(`?${params.toString()}`)
}
return (
<Select value={category} onValueChange={setCategory}>
{/* options */}
</Select>
)
}
motion-purposeful - Animations should enhance UX, not distractmotion-performance - Use transform/opacity, avoid layout triggersmotion-reduced-motion - Respect prefers-reduced-motionmotion-layout-id - Use layoutId for shared element transitionsmotion-exit-animations - Use AnimatePresence for exit animationsmotion-variants - Define reusable animation statesnpm install motion
Motion (formerly Framer Motion) provides declarative animations that enhance user experience.
Basic Animations
'use client'
import { motion } from 'motion/react'
function FadeInCard({ children }: { children: React.ReactNode }) {
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
className="rounded-lg border p-4"
>
{children}
</motion.div>
)
}
Interaction States
function InteractiveButton({ children }: { children: React.ReactNode }) {
return (
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
transition={{ type: 'spring', stiffness: 400, damping: 17 }}
className="px-4 py-2 bg-primary text-primary-foreground rounded-md"
>
{children}
</motion.button>
)
}
Exit Animations with AnimatePresence
import { motion, AnimatePresence } from 'motion/react'
function NotificationList({ notifications }: { notifications: Notification[] }) {
return (
<AnimatePresence>
{notifications.map((notification) => (
<motion.div
key={notification.id}
initial={{ opacity: 0, x: 50 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -50 }}
transition={{ duration: 0.2 }}
>
<Notification data={notification} />
</motion.div>
))}
</AnimatePresence>
)
}
Shared Element Transitions
function ProductGrid({ products }: { products: Product[] }) {
const [selected, setSelected] = useState<Product | null>(null)
return (
<>
<div className="grid grid-cols-3 gap-4">
{products.map((product) => (
<motion.div
key={product.id}
layoutId={`product-${product.id}`}
onClick={() => setSelected(product)}
className="cursor-pointer"
>
<img src={product.image} alt={product.name} />
</motion.div>
))}
</div>
<AnimatePresence>
{selected && (
<motion.div
layoutId={`product-${selected.id}`}
className="fixed inset-0 flex items-center justify-center"
>
<ProductDetail product={selected} onClose={() => setSelected(null)} />
</motion.div>
)}
</AnimatePresence>
</>
)
}
Reusable Variants
const fadeInUp = {
initial: { opacity: 0, y: 20 },
animate: { opacity: 1, y: 0 },
exit: { opacity: 0, y: -20 },
}
const staggerContainer = {
animate: {
transition: {
staggerChildren: 0.1,
},
},
}
function StaggeredList({ items }: { items: string[] }) {
return (
<motion.ul variants={staggerContainer} initial="initial" animate="animate">
{items.map((item, i) => (
<motion.li key={i} variants={fadeInUp}>
{item}
</motion.li>
))}
</motion.ul>
)
}
Scroll-Triggered Animations
import { motion, useInView } from 'motion/react'
import { useRef } from 'react'
function ScrollReveal({ children }: { children: React.ReactNode }) {
const ref = useRef(null)
const isInView = useInView(ref, { once: true, margin: '-100px' })
return (
<motion.div
ref={ref}
initial={{ opacity: 0, y: 50 }}
animate={isInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 50 }}
transition={{ duration: 0.5 }}
>
{children}
</motion.div>
)
}
Respecting Reduced Motion
import { motion, useReducedMotion } from 'motion/react'
function AccessibleAnimation({ children }: { children: React.ReactNode }) {
const shouldReduceMotion = useReducedMotion()
return (
<motion.div
initial={{ opacity: 0, y: shouldReduceMotion ? 0 : 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: shouldReduceMotion ? 0 : 0.3 }}
>
{children}
</motion.div>
)
}
transform and opacity for smooth 60fps animationswillChange prop for complex animationsuseInView to lazy-load animationswidth, height, top, left directlyrerender-memo - Extract expensive work into memoized componentsrerender-usememo - Memoize expensive calculationsrerender-usecallback - Stabilize callback referencesrerender-dependencies - Use primitive dependencies in effectsrerender-transitions - Use startTransition for non-urgent updatesMemoization for Expensive Components
import { memo } from 'react'
const ExpensiveList = memo(function ExpensiveList({
items
}: {
items: Item[]
}) {
return (
<ul>
{items.map(item => (
<li key={item.id}>{/* expensive render */}</li>
))}
</ul>
)
})
Stable Callbacks
function Parent() {
const [count, setCount] = useState(0)
// Stable reference - won't cause child re-renders
const handleClick = useCallback(() => {
setCount(c => c + 1)
}, [])
return <MemoizedChild onClick={handleClick} />
}
Non-Urgent Updates with Transitions
function SearchResults() {
const [query, setQuery] = useState('')
const [results, setResults] = useState([])
const [isPending, startTransition] = useTransition()
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
setQuery(e.target.value) // Urgent: update input immediately
startTransition(() => {
setResults(filterResults(e.target.value)) // Non-urgent: can be interrupted
})
}
return (
<>
<Input value={query} onChange={handleChange} />
{isPending && <Spinner />}
<ResultsList results={results} />
</>
)
}
a11y-semantic-html - Use correct HTML elementsa11y-keyboard-nav - Ensure keyboard navigabilitya11y-aria-labels - Add descriptive labels for screen readersa11y-focus-management - Manage focus in modals and dynamic contenta11y-color-contrast - Ensure sufficient color contrastSemantic HTML
// Incorrect: div soup
<div onClick={handleClick}>Click me</div>
// Correct: semantic button
<button onClick={handleClick}>Click me</button>
Focus Management in Modals
function Modal({ isOpen, onClose, children }) {
const closeButtonRef = useRef<HTMLButtonElement>(null)
useEffect(() => {
if (isOpen) {
closeButtonRef.current?.focus()
}
}, [isOpen])
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent>
{children}
<Button ref={closeButtonRef} onClick={onClose}>
Close
</Button>
</DialogContent>
</Dialog>
)
}
Skip Links
function Layout({ children }) {
return (
<>
<a
href="#main-content"
className="sr-only focus:not-sr-only focus:absolute focus:top-4 focus:left-4"
>
Skip to main content
</a>
<Header />
<main id="main-content">{children}</main>
</>
)
}
ts-strict-mode - Enable strict TypeScript configurationts-component-props - Define explicit prop interfacests-generics - Use generics for reusable componentsts-discriminated-unions - Use for state machinests-infer-when-possible - Let TypeScript infer when obviousComponent Props
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'default' | 'destructive' | 'outline'
size?: 'sm' | 'md' | 'lg'
isLoading?: boolean
}
function Button({
variant = 'default',
size = 'md',
isLoading,
children,
disabled,
...props
}: ButtonProps) {
return (
<button
disabled={disabled || isLoading}
{...props}
>
{isLoading ? <Spinner /> : children}
</button>
)
}
Discriminated Unions for State
type AsyncState<T> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: Error }
function useAsync<T>(asyncFn: () => Promise<T>) {
const [state, setState] = useState<AsyncState<T>>({ status: 'idle' })
// TypeScript knows exact shape based on status
if (state.status === 'success') {
return state.data // TypeScript knows data exists
}
}
Generic Components
interface SelectProps<T> {
options: T[]
value: T
onChange: (value: T) => void
getLabel: (option: T) => string
getValue: (option: T) => string
}
function Select<T>({ options, value, onChange, getLabel, getValue }: SelectProps<T>) {
return (
<select
value={getValue(value)}
onChange={(e) => {
const selected = options.find(o => getValue(o) === e.target.value)
if (selected) onChange(selected)
}}
>
{options.map((option) => (
<option key={getValue(option)} value={getValue(option)}>
{getLabel(option)}
</option>
))}
</select>
)
}
useActionState - Form state management
'use client'
import { useActionState } from 'react'
function SubscribeForm() {
const [state, formAction, isPending] = useActionState(
async (prevState, formData) => {
const email = formData.get('email')
const result = await subscribe(email)
return result
},
null
)
return (
<form action={formAction}>
<Input name="email" type="email" />
<Button type="submit" disabled={isPending}>
{isPending ? 'Subscribing...' : 'Subscribe'}
</Button>
{state?.error && <p className="text-red-500">{state.error}</p>}
</form>
)
}
useOptimistic - Optimistic UI updates
'use client'
import { useOptimistic } from 'react'
function TodoList({ todos }: { todos: Todo[] }) {
const [optimisticTodos, addOptimisticTodo] = useOptimistic(
todos,
(state, newTodo: Todo) => [...state, newTodo]
)
async function addTodo(formData: FormData) {
const title = formData.get('title') as string
const newTodo = { id: crypto.randomUUID(), title, completed: false }
addOptimisticTodo(newTodo) // Immediately show in UI
await createTodo(title) // Then persist to server
}
return (
<>
<form action={addTodo}>
<Input name="title" />
<Button type="submit">Add</Button>
</form>
<ul>
{optimisticTodos.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
</>
)
}
use - Async resource reading
import { use, Suspense } from 'react'
async function fetchUser(id: string): Promise<User> {
const res = await fetch(`/api/users/${id}`)
return res.json()
}
function UserProfile({ userPromise }: { userPromise: Promise<User> }) {
const user = use(userPromise) // Suspends until resolved
return <div>{user.name}</div>
}
function Page({ userId }: { userId: string }) {
const userPromise = fetchUser(userId)
return (
<Suspense fallback={<UserSkeleton />}>
<UserProfile userPromise={userPromise} />
</Suspense>
)
}
src/
├── app/ # Next.js App Router
│ ├── layout.tsx
│ ├── page.tsx
│ └── (routes)/
├── components/
│ ├── ui/ # shadcn/ui components
│ │ ├── button.tsx
│ │ ├── card.tsx
│ │ └── ...
│ └── features/ # Feature-specific components
│ ├── auth/
│ └── dashboard/
├── hooks/ # Custom hooks
├── lib/ # Utilities
│ ├── utils.ts # cn() helper, etc.
│ └── validations.ts # Zod schemas
├── actions/ # Server Actions
└── types/ # TypeScript types
Weekly Installs
94
Repository
GitHub Stars
2
First Seen
Jan 21, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
claude-code78
opencode76
github-copilot71
codex71
gemini-cli69
cursor64
Genkit JS 开发指南:AI 应用构建、错误排查与最佳实践
7,700 周安装