frontend-patterns
This Claude Code skill provides modern frontend development patterns for React and Next.js applications, covering component composition, state management approaches like useState and Zustand, data fetching strategies, performance optimization techniques including memoization and code splitting, form handling with validation, and accessible responsive UI patterns. Use it when building React components, managing application state, implementing data fetching, optimizing performance, handling forms, managing client-side routing, or creating accessible user interfaces.
git clone --depth 1 https://github.com/xu-xiang/everything-claude-code-zh /tmp/frontend-patterns && cp -r /tmp/frontend-patterns/.agents/skills/frontend-patterns ~/.claude/skills/frontend-patternsSKILL.md
# 前端开发模式 (Frontend Development Patterns)
适用于 React、Next.js 和高性能用户界面的现代前端模式。
## 何时激活 (When to Activate)
- 构建 React 组件(组合、Props、渲染)时
- 管理状态(useState、useReducer、Zustand、Context)时
- 实现数据获取(SWR、React Query、服务端组件)时
- 优化性能(记忆化、虚拟化、代码分割)时
- 处理表单(验证、受控输入、Zod 模式)时
- 处理客户端路由和导航时
- 构建具备可访问性(Accessible)且响应式的 UI 模式时
## 组件模式 (Component Patterns)
### 组合优于继承 (Composition Over Inheritance)
```typescript
// ✅ 推荐:组件组合 (Component composition)
interface CardProps {
children: React.ReactNode
variant?: 'default' | 'outlined'
}
export function Card({ children, variant = 'default' }: CardProps) {
return <div className={`card card-${variant}`}>{children}</div>
}
export function CardHeader({ children }: { children: React.ReactNode }) {
return <div className="card-header">{children}</div>
}
export function CardBody({ children }: { children: React.ReactNode }) {
return <div className="card-body">{children}</div>
}
// 使用示例
<Card>
<CardHeader>标题</CardHeader>
<CardBody>内容</CardBody>
</Card>
```
### 复合组件 (Compound Components)
```typescript
interface TabsContextValue {
activeTab: string
setActiveTab: (tab: string) => void
}
const TabsContext = createContext<TabsContextValue | undefined>(undefined)
export function Tabs({ children, defaultTab }: {
children: React.ReactNode
defaultTab: string
}) {
const [activeTab, setActiveTab] = useState(defaultTab)
return (
<TabsContext.Provider value={{ activeTab, setActiveTab }}>
{children}
</TabsContext.Provider>
)
}
export function TabList({ children }: { children: React.ReactNode }) {
return <div className="tab-list">{children}</div>
}
export function Tab({ id, children }: { id: string, children: React.ReactNode }) {
const context = useContext(TabsContext)
if (!context) throw new Error('Tab 必须在 Tabs 内部使用')
return (
<button
className={context.activeTab === id ? 'active' : ''}
onClick={() => context.setActiveTab(id)}
>
{children}
</button>
)
}
// 使用示例
<Tabs defaultTab="overview">
<TabList>
<Tab id="overview">概览</Tab>
<Tab id="details">详情</Tab>
</TabList>
</Tabs>
```
### 渲染属性模式 (Render Props Pattern)
```typescript
interface DataLoaderProps<T> {
url: string
children: (data: T | null, loading: boolean, error: Error | null) => React.ReactNode
}
export function DataLoader<T>({ url, children }: DataLoaderProps<T>) {
const [data, setData] = useState<T | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<Error | null>(null)
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(setData)
.catch(setError)
.finally(() => setLoading(false))
}, [url])
return <>{children(data, loading, error)}</>
}
// 使用示例
<DataLoader<Market[]> url="/api/markets">
{(markets, loading, error) => {
if (loading) return <Spinner />
if (error) return <Error error={error} />
return <MarketList markets={markets!} />
}}
</DataLoader>
```
## 自定义钩子模式 (Custom Hooks Patterns)
### 状态管理钩子 (State Management Hook)
```typescript
export function useToggle(initialValue = false): [boolean, () => void] {
const [value, setValue] = useState(initialValue)
const toggle = useCallback(() => {
setValue(v => !v)
}, [])
return [value, toggle]
}
// 使用示例
const [isOpen, toggleOpen] = useToggle()
```
### 异步数据获取钩子 (Async Data Fetching Hook)
```typescript
interface UseQueryOptions<T> {
onSuccess?: (data: T) => void
onError?: (error: Error) => void
enabled?: boolean
}
export function useQuery<T>(
key: string,
fetcher: () => Promise<T>,
options?: UseQueryOptions<T>
) {
const [data, setData] = useState<T | null>(null)
const [error, setError] = useState<Error | null>(null)
const [loading, setLoading] = useState(false)
const refetch = useCallback(async () => {
setLoading(true)
setError(null)
try {
const result = await fetcher()
setData(result)
options?.onSuccess?.(result)
} catch (err) {
const error = err as Error
setError(error)
options?.onError?.(error)
} finally {
setLoading(false)
}
}, [fetcher, options])
useEffect(() => {
if (options?.enabled !== false) {
refetch()
}
}, [key, refetch, options?.enabled])
return { data, error, loading, refetch }
}
// 使用示例
const { data: markets, loading, error, refetch } = useQuery(
'markets',
() => fetch('/api/markets').then(r => r.json()),
{
onSuccess: data => console.log('已获取', data.length, '个市场'),
onError: err => console.error('失败:', err)
}
)
```
### 防抖钩子 (Debounce Hook)
```typescript
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value)
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value)
}, delay)
return () => clearTimeout(handler)
}, [value, delay])
return debouncedValue
}
// 使用示例
const [searchQuery, setSearchQuery] = useState('')
const debouncedQuery = useDebounce(searchQuery, 500)
useEffect(() => {
if (debouncedQuery) {
performSearch(debouncedQuery)
}
}, [debouncedQuery])
```
## 状态管理模式 (State Management Patterns)
### Context + Reducer 模式 (Context + Reducer Pattern)
```typescript
interface State {
markets: Market[]
selectedMarket: Market | null
loading: boolean
}
type Action =
| { type: 'SET_MARKETS'; payload: Market[] }
| { type: 'SELECT_MARKET'; payload: Market }
| { type: 'SET_LOADING'; payload: boolean }
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'SET_MARKETS':
return { ...state, markets: action.payload }
case 'SELECT_MARKET':
return { ...state, selectedMarket: action.payload }
case 'SET_LOADING':
return { ...state, loading: action.payload }
default:
return state
}
}
const MarketContext = createContext<{
state: State
dispatch: Dispatch<Action>
} | undefined>(undefined)
export function MarketProvider({生产级 API 的 REST API 设计模式,包括资源命名、状态码、分页、过滤、错误响应、版本控制和速率限制。
编写文章、指南、博客、教程、时事通讯(Newsletter)等长内容,支持从示例或品牌指南中提取独特的语感语调。适用于需要撰写超过一个段落的精炼文本,尤其是对语气一致性、结构和可信度有较高要求时。
后端架构模式、API 设计、数据库优化以及 Node.js、Express 和 Next.js API 路由的服务端最佳实践。
TypeScript、JavaScript、React、Node.js 开发的通用编码标准、最佳实践和模式。
为 X、LinkedIn、TikTok、YouTube、时事通讯(Newsletters)以及跨平台内容重加工营销活动(Repurposed multi-platform campaigns)创建平台原生的内容系统。当用户需要社交媒体帖子、推文串(Threads)、脚本、内容日历,或将单一源素材清晰地适配到多个平台时使用。
Playwright E2E 测试模式、页面对象模型(POM)、配置、CI/CD 集成、产物管理以及不稳定测试(flaky test)策略。
适用于 Claude Code 会话的正规评测框架(Evaluation Framework),实现了评测驱动开发(Eval-Driven Development, EDD)原则
从零开始或通过转换 PowerPoint 文件创建令人惊叹、动画丰富的 HTML 演示文稿(Presentations)。适用于用户想要构建演示文稿、将 PPT/PPTX 转换为 Web 页面或为演讲/路演创建幻灯片(Slides)的场景。通过视觉探索而非抽象选择,帮助非设计师发掘其审美偏好。