Tips & Tricks

Claude Code के साथ Streamline Frontend State Management कैसे करें

Claude Code का उपयोग करके streamline frontend state management सीखें। Practical code examples और step-by-step guidance शामिल है।

状態managementの設計にClaude Codeが役立つ理由

フロントエンドの状態managementは、アプリのcomplexさに応じてアプローチを変えるज़रूरीがあり है।Claude CodeはProject全体の状態の流れを理解したऊपरで、appropriateなlibraryの選定と設計patternの提案ができ है।

Zustandによる状態management

軽量で学習コストが低いZustandは、多くのProjectで採用されてい है।

> Zustandでauthentication状態とuser情報をmanagementするストアをबनाओ。
> localstorageへの永続化もimplement करो。
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,
      }),
    }
  )
);

asyncdataのmanagement(TanStack Queryintegration)

> TanStack Queryで商品listのフェッチ、cache、楽観的updateをimplement करो。
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

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

// 商品listのfetch
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分बीचcache
  });
}

// 商品のupdate(楽観的update)
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によるアトミックな状態management

> Jotaiでthemesettingsとsidebarの開閉状態をmanagementするアトムをबनाओ。
import { atom, useAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';

// themeの状態(localstorageに永続化)
export const themeAtom = atomWithStorage<'light' | 'dark'>('theme', 'light');

// sidebarの開閉状態
export const sidebarOpenAtom = atom(true);

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

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

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

状態managementlibraryの選定

Claude CodeにProjectに合った状態managementlibraryの選定を依頼でき है।

> इसProjectの状態managementके बारे में分析して。
> 現在のContext APIのuse करने का तरीकाを評価して、
> よりappropriateなlibraryがあれば移行プランを提案して。
library適したケース
useState/useReducercomponentlocalな状態
Zustandグローバルな状態、シンプルなAPI
Jotai細粒度のリアクティブ状態
TanStack Queryserver状態のcachemanagement
Redux Toolkit大規模アプリ、complexなビジネスロジック

Summary

Claude Code का उपयोग करके、Projectの要件に合った状態managementpatternの選定 सेimplementation तकefficiently進められ है।プロンプトでアプリの構造と要件をspecifically伝える बातがimportant है।効果的なプロンプトのलिखने का तरीकाはプロンプトテクニックcomplete guideをदेखें。また生産性を3倍にするTipsでフロントエンドdevelopment全般のefficiency improvementテクニックも紹介してい है।

Claude Codeके details के लिएAnthropicofficial documentationदेखें。

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