Chuyển đến nội dung
Skillpedia
Website và giao diện (frontend)48k · #5582

react-state-management

Skill này làm gì

Công cụ này giúp tổ chức và quản lý thông tin quan trọng trong ứng dụng xây dựng bằng React. Nó có nhiều cách khác nhau để lưu và truy cập dữ liệu, như thông tin người dùng hoặc dữ liệu từ máy chủ.

Khi nào nên dùng

  • ✓Khi xây dựng ứng dụng React cần chia sẻ dữ liệu giữa nhiều phần.
  • ✓Khi quyết định cách tốt nhất để lưu dữ liệu lấy từ máy chủ.
  • ✓Khi cố sửa lỗi dữ liệu của ứng dụng không hiển thị đúng.

Liên kết skill

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/react-state-management/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/react-state-management/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để tổ chức dữ liệu của ứng dụng React để các phần khác nhau dùng được dễ dàng?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Công cụ so sánh các phương pháp (như Redux Toolkit, Zustand, Jotai, React Query) và đưa ra ví dụ cách thiết lập. Bạn có thể chọn công cụ phù hợp nhất với quy mô và độ phức tạp của dự án.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

React State Management

Comprehensive guide to modern React state management patterns, from local component state to global stores and server state synchronization.

Do not use this skill when

  • The task is unrelated to react state management
  • You need a different domain or tool outside this scope

Instructions

  • Clarify goals, constraints, and required inputs.
  • Apply relevant best practices and validate outcomes.
  • Provide actionable steps and verification.

Use this skill when

  • Setting up global state management in a React app
  • Choosing between Redux Toolkit, Zustand, or Jotai
  • Managing server state with React Query or SWR
  • Implementing optimistic updates
  • Debugging state-related issues
  • Migrating from legacy Redux to modern patterns

Core Concepts

1. State Categories

Type Description Solutions
Local State Component-specific, UI state useState, useReducer
Global State Shared across components Redux Toolkit, Zustand, Jotai
Server State Remote data, caching React Query, SWR, RTK Query
URL State Route parameters, search React Router, nuqs
Form State Input values, validation React Hook Form, Formik

2. Selection Criteria

Small app, simple state → Zustand or Jotai
Large app, complex state → Redux Toolkit
Heavy server interaction → React Query + light client state
Atomic/granular updates → Jotai

Quick Start

Zustand (Simplest)

// store/useStore.ts
import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'

interface AppState {
  user: User | null
  theme: 'light' | 'dark'
  setUser: (user: User | null) => void
  toggleTheme: () => void
}

export const useStore = create<AppState>()(
  devtools(
    persist(
      (set) => ({
        user: null,
        theme: 'light',
        setUser: (user) => set({ user }),
        toggleTheme: () => set((state) => ({
          theme: state.theme === 'light' ? 'dark' : 'light'
        })),
      }),
      { name: 'app-storage' }
    )
  )
)

// Usage in component
function Header() {
  const { user, theme, toggleTheme } = useStore()
  return (
    <header className={theme}>
      {user?.name}
      <button onClick={toggleTheme}>Toggle Theme</button>
    </header>
  )
}

Patterns

Pattern 1: Redux Toolkit with TypeScript

// store/index.ts
import { configureStore } from '@reduxjs/toolkit'
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
import userReducer from './slices/userSlice'
import cartReducer from './slices/cartSlice'

export const store = configureStore({
  reducer: {
    user: userReducer,
    cart: cartReducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: ['persist/PERSIST'],
      },
    }),
})

export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

// Typed hooks
export const useAppDispatch: () => AppDispatch = useDispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
// store/slices/userSlice.ts
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit'

interface User {
  id: string
  email: string
  name: string
}

interface UserState {
  current: User | null
  status: 'idle' | 'loading' | 'succeeded' | 'failed'
  error: string | null
}

const initialState: UserState = {
  current: null,
  status: 'idle',
  error: null,
}

export const fetchUser = createAsyncThunk(
  'user/fetchUser',
  async (userId: string, { rejectWithValue }) => {
    try {
      const response = await fetch(`/api/users/${userId}`)
      if (!response.ok) throw new Error('Failed to fetch user')
      return await response.json()
    } catch (error) {
      return rejectWithValue((error as Error).message)
    }
  }
)

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    setUser: (state, action: PayloadAction<User>) => {
      state.current = action.payload
      state.status = 'succeeded'
    },
    clearUser: (state) => {
      state.current = null
      state.status = 'idle'
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchUser.pending, (state) => {
        state.status = 'loading'
        state.error = null
      })
      .addCase(fetchUser.fulfilled, (state, action) => {

…
Câu hỏi thường gặp

Khác nhau giữa trạng thái cục bộ và toàn cục là gì?

Trạng thái cục bộ chỉ thuộc về một thành phần (như nút đổi màu), còn trạng thái toàn cục được nhiều thành phần dùng chung (như chế độ sáng/tối của ứng dụng).

Khi nào nên dùng React Query?

React Query phù hợp khi bạn cần lấy, lưu tạm và đồng bộ dữ liệu từ máy chủ, giúp trải nghiệm người dùng nhanh hơn.

Công cụ đơn giản nhất để bắt đầu là gì?

Zustand thường được khuyên dùng vì đơn giản hơn để quản lý trạng thái toàn cục so với các công cụ khác.

Chi tiết

Mô tả gốc của tác giả

Master modern React state management with Redux Toolkit, Zustand, Jotai, and React Query. Use when setting up global state, managing server state, or choosing between state management solutions.

repo: sickn33/agentic-awesome-skills

Độ phổ biến

Sao GitHub
48k
Vị trí xếp hạng
#5582
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự