Tips & Tricks

Gestion de estado con Claude Code

Aprenda sobre gestion de estado usando Claude Code. Incluye consejos practicos y ejemplos de codigo.

状態管理の設計に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大規模アプリ、複雑なビジネスロジック

Summary

Claude Codeを使えば、プロジェクトの要件に合った状態管理パターンの選定から実装まで効率的に進められます。プロンプトでアプリの構造と要件を具体的に伝えることが重要です。効果的なプロンプトの書き方はプロンプトテクニック完全ガイドを参照してください。また生産性を3倍にするTipsでフロントエンド開発全般の効率化テクニックも紹介しています。

Claude Codeの詳細はAnthropic公式ドキュメントをご覧ください。

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