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 设计模式,包括资源命名、状态码、分页、过滤、错误响应、版本控制和速率限制。
用于系统设计、可扩展性及技术决策的软件架构专家。在规划新功能、重构大型系统或做出架构决策时请主动(PROACTIVELY)使用。
编写文章、指南、博客、教程、时事通讯(Newsletter)等长内容,支持从示例或品牌指南中提取独特的语感语调。适用于需要撰写超过一个段落的精炼文本,尤其是对语气一致性、结构和可信度有较高要求时。
后端架构模式、API 设计、数据库优化以及 Node.js、Express 和 Next.js API 路由的服务端最佳实践。
构建与 TypeScript 错误修复专家。当构建失败或出现类型错误时,请主动(PROACTIVELY)使用。仅修复构建/类型错误,保持最小差异(diff),不进行架构性修改。重点是快速使构建通过(get the build green)。
个人通讯幕僚 (Chief of Staff),负责分拣电子邮件、Slack、LINE 和 Messenger。将消息分类为 4 个级别 (skip/info_only/meeting_info/action_required),生成草稿回复,并通过钩子 (Hooks) 强制执行发送后的后续跟进。适用于管理多渠道通讯工作流。
启动 NanoClaw 智能体 (Agent) REPL — 一个由 claude CLI 驱动的持久化、会话感知 (session-aware) 的 AI 助手。
ClickHouse 数据库模式、查询优化、分析以及高性能分析工作负载的数据工程最佳实践。