Tips & Tricks

如何Streamline Frontend State Management:Claude Code 实战指南

学习如何streamline frontend state management:Claude Code 实战. 包含实用代码示例和分步指导。

状態管理の设计にClaude Code 役立つ理由

前端の状態管理は、应用の複雑さに応じてアプローチを変える必要があります。Claude Code 项目全体の状態の流れを理解した上で、合适的库の選定と设计パターンの提案が可以。

Zustand通过状態管理

軽量で学習コストが低いZustandは、多くの项目で採用されています。

> Zustandで认证状態と用户情報を管理するストア创建。
> ローカル存储への永続化も实现して。
import { create } from 'zustand';
import { persist } from 'zustand/middleware';

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

interface AuthState {
  user: User | null;
  token: string | null;
  isAuthenticated: boolean;
  login: (email: string, password: string) => Promise<void>;
  logout: () => void;
  updateProfile: (data: Partial<User>) => void;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      user: null,
      token: null,
      isAuthenticated: false,

      login: async (email, password) => {
        const res = await fetch('/api/auth/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email, password }),
        });
        if (!res.ok) throw new Error('Login failed');

        const { user, token } = await res.json();
        set({ user, token, isAuthenticated: true });
      },

      logout: () => {
        set({ user: null, token: null, isAuthenticated: false });
      },

      updateProfile: (data) => {
        const current = get().user;
        if (current) {
          set({ user: { ...current, ...data } });
        }
      },
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({
        user: state.user,
        token: state.token,
        isAuthenticated: state.isAuthenticated,
      }),
    }
  )
);

异步数据の管理(TanStack Query联动)

> TanStack Queryで商品列表のフェッチ、缓存、楽観的更新实现。
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

interface Product {
  id: string;
  name: string;
  price: number;
  stock: number;
}

// 商品列表の获取
export function useProducts(page: number = 1) {
  return useQuery({
    queryKey: ['products', page],
    queryFn: async () => {
      const res = await fetch(`/api/products?page=${page}`);
      return res.json() as Promise<{ items: Product[]; total: number }>;
    },
    staleTime: 5 * 60 * 1000, // 5分間缓存
  });
}

// 商品の更新(楽観的更新)
export function useUpdateProduct() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ id, data }: { id: string; data: Partial<Product> }) => {
      const res = await fetch(`/api/products/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      });
      return res.json() as Promise<Product>;
    },

    onMutate: async ({ id, data }) => {
      await queryClient.cancelQueries({ queryKey: ['products'] });
      const previous = queryClient.getQueryData(['products']);

      queryClient.setQueriesData(
        { queryKey: ['products'] },
        (old: { items: Product[]; total: number } | undefined) => {
          if (!old) return old;
          return {
            ...old,
            items: old.items.map(p =>
              p.id === id ? { ...p, ...data } : p
            ),
          };
        }
      );

      return { previous };
    },

    onError: (_err, _vars, context) => {
      if (context?.previous) {
        queryClient.setQueryData(['products'], context.previous);
      }
    },

    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ['products'] });
    },
  });
}

Jotai通过アトミックな状態管理

> Jotaiで主题配置と侧边栏の開閉状態を管理するアトム创建。
import { atom, useAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';

// 主题の状態(ローカル存储に永続化)
export const themeAtom = atomWithStorage<'light' | 'dark'>('theme', 'light');

// 侧边栏の開閉状態
export const sidebarOpenAtom = atom(true);

// 派生アトム:主题に応じたCSS类
export const themeClassAtom = atom((get) => {
  const theme = get(themeAtom);
  return theme === 'dark' ? 'dark bg-gray-900 text-white' : 'bg-white text-gray-900';
});

// 组件での使用例
function ThemeToggle() {
  const [theme, setTheme] = useAtom(themeAtom);

  return (
    <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
      {theme === 'light' ? 'Dark Mode' : 'Light Mode'}
    </button>
  );
}

状態管理库の選定

让 Claude Code项目に合った状態管理库の選定を依頼可以。

> 这个项目の状態管理关于分析して。
> 現在のContext APIの使い方を評価して、
> より合适的库があれば移行プランを提案して。
適したケース
useState/useReducer组件ローカルな状態
Zustandグローバルな状態、シンプルなAPI
Jotai細粒度のリアクティブ状態
TanStack Query服务器状態の缓存管理
Redux Toolkit大規模应用、複雑なビジネスロジック

总结

借助 Claude Code,项目の要件に合った状態管理パターンの選定から实现まで高效地進められます。プロンプトで应用の構造と要件を具体地伝えることが很重要。有效的プロンプトの書き方はプロンプトテクニック完全指南。此外生産性を3倍にするTipsで前端开发全般の效率化テクニックも紹介しています。

Claude Code 的详细信息请参阅Anthropic官方文档

#Claude Code #React #state management #Zustand #frontend