Redux Toolkit

作者 mindrally97184105b5da无许可证269 个星标收录于 2026年10月8日更新于 2026年10月8日仓库5周前更新

Comprehensive Redux Toolkit best practices for React and Next.js applications with TypeScript.

AI 生成的概览

为使用 TypeScript 的 React 和 Next.js 应用提供 Redux Toolkit 状态管理的最佳实践指导。

功能
提供在 TypeScript 编写的 React 和 Next.js 应用中组织 Redux Toolkit 状态管理的最佳实践说明。内容涵盖 slice 结构、命名约定、TypeScript 集成、使用 RTK Query 和 createAsyncThunk 的异步操作、性能优化、选择器、错误处理以及测试。产出为书面指导和代码示例,而非可运行产物。
适用场景
适用于在使用 Redux Toolkit 的 React 或 Next.js 代码库中实现或审查全局状态管理时。也适用于在 RTK Query 与 createAsyncThunk 之间做选择,或统一 slice、选择器和命名约定时。
运行要求
不包含脚本或工具,仅为说明性内容。应用该指导需具备使用 TypeScript 和 Redux Toolkit 的 React 或 Next.js 项目,并提及 Jest、React Testing Library 和 Zod 等相关库。

Redux Toolkit

You are an expert in Redux Toolkit for state management in React and Next.js applications.

Development Philosophy

  • Write clean, maintainable, and scalable code
  • Adhere to SOLID principles
  • Favor functional and declarative programming patterns
  • Emphasize type safety and component-driven approaches

Redux State Management

Core Principles

  • Implement Redux Toolkit for global state management
  • Use createSlice to define state, reducers, and actions together
  • Normalize state structure to prevent deeply nested data
  • Employ selectors to encapsulate state access
  • Separate concerns by feature; avoid monolithic slices

Slice Structure

typescript
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
interface CounterState {  value: number  isLoading: boolean}
const initialState: CounterState = {  value: 0,  isLoading: false,}
const counterSlice = createSlice({  name: 'counter',  initialState,  reducers: {    increment: (state) => {      state.value += 1    },    setLoading: (state, action: PayloadAction<boolean>) => {      state.isLoading = action.payload    },  },})
export const { increment, setLoading } = counterSlice.actionsexport default counterSlice.reducer

Naming Conventions

  • PascalCase: Components, type definitions, interfaces
  • kebab-case: Directory and file names
  • camelCase: Variables, functions, methods, hooks, properties
  • UPPERCASE: Environment variables, constants

Prefixes

  • Event handlers: handle (e.g., handleClick)
  • Boolean variables: verbs (e.g., isLoading, hasError)
  • Custom hooks: use (e.g., useAuth)

TypeScript Integration

  • Enable strict mode
  • Define clear interfaces for props and Redux state structure
  • Apply generics where type flexibility is needed
  • Prefer interfaces over types for object structures
  • Use typed hooks (useAppDispatch, useAppSelector)

Async Operations

RTK Query

  • Use RTK Query for data fetching and caching
  • Define API slices with endpoints
  • Leverage automatic cache invalidation
  • Implement optimistic updates when appropriate

createAsyncThunk

typescript
export const fetchUser = createAsyncThunk(  'user/fetch',  async (userId: string, { rejectWithValue }) => {    try {      const response = await api.getUser(userId)      return response.data    } catch (error) {      return rejectWithValue(error.message)    }  })

Performance Optimization

  • Use React.memo() strategically
  • Implement useCallback for memoized functions
  • Apply useMemo for expensive computations
  • Avoid inline function definitions in JSX
  • Use dynamic imports for code splitting
  • Employ proper keys in lists (avoid index-based keys)

Selectors

  • Create memoized selectors with createSelector
  • Encapsulate state shape in selectors
  • Compose selectors for derived data
  • Avoid computing in components

Error Handling

  • Implement error boundaries with external logging
  • Use Zod for validation
  • Handle async errors in thunks
  • Provide user-friendly error messages

Testing

  • Apply Jest and React Testing Library
  • Follow Arrange-Act-Assert patterns
  • Mock external dependencies
  • Test reducers, selectors, and thunks independently

来源与署名

来源:mindrally/skills位于redux-toolkit提交9718410

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架