Claude Code के साथ Zustand
Claude Code का उपयोग करके zustand सीखें। Practical tips और code examples शामिल हैं।
Zustandでシンプルかつpowerfulな状態managementを実現する
Zustandは最小限のAPIでpowerfulな状態managementを提供するReact向けlibrary है।Reduxの तरहなcomplexなボイラープレートが不要で、TypeScriptとの相性も抜群 है।Claude Codeはストア設計 सेoptimization तक的確にサポートしてくれ है।
basic ストア設計
Claude Codeにストアの設計を依頼 करें।
> Zustandでショッピングcartのストアをबनाओ。
> 商品add、delete、数量変更、合計計算を含めて。TypeScriptsupportで。
import { create } from "zustand";
interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
}
interface CartStore {
items: CartItem[];
addItem: (item: Omit<CartItem, "quantity">) => void;
removeItem: (id: string) => void;
updateQuantity: (id: string, quantity: number) => void;
clearCart: () => void;
totalItems: () => number;
totalPrice: () => number;
}
export const useCartStore = create<CartStore>((set, get) => ({
items: [],
addItem: (item) =>
set((state) => {
const existing = state.items.find((i) => i.id === item.id);
if (existing) {
return {
items: state.items.map((i) =>
i.id === item.id ? { ...i, quantity: i.quantity + 1 } : i
),
};
}
return { items: [...state.items, { ...item, quantity: 1 }] };
}),
removeItem: (id) =>
set((state) => ({
items: state.items.filter((i) => i.id !== id),
})),
updateQuantity: (id, quantity) =>
set((state) => ({
items: state.items.map((i) =>
i.id === id ? { ...i, quantity: Math.max(0, quantity) } : i
).filter((i) => i.quantity > 0),
})),
clearCart: () => set({ items: [] }),
totalItems: () => get().items.reduce((sum, i) => sum + i.quantity, 0),
totalPrice: () =>
get().items.reduce((sum, i) => sum + i.price * i.quantity, 0),
}));
middlewareのutilization
Zustandのmiddlewareで永続化やlog出力をaddでき है।
import { create } from "zustand";
import { persist, devtools, subscribeWithSelector } from "zustand/middleware";
import { immer } from "zustand/middleware/immer";
interface AppStore {
theme: "light" | "dark";
locale: string;
notifications: Notification[];
setTheme: (theme: "light" | "dark") => void;
setLocale: (locale: string) => void;
addNotification: (notification: Notification) => void;
removeNotification: (id: string) => void;
}
export const useAppStore = create<AppStore>()(
devtools(
persist(
immer(
subscribeWithSelector((set) => ({
theme: "light",
locale: "ja",
notifications: [],
setTheme: (theme) =>
set((state) => {
state.theme = theme;
}),
setLocale: (locale) =>
set((state) => {
state.locale = locale;
}),
addNotification: (notification) =>
set((state) => {
state.notifications.push(notification);
}),
removeNotification: (id) =>
set((state) => {
state.notifications = state.notifications.filter(
(n) => n.id !== id
);
}),
}))
),
{
name: "app-store",
partialize: (state) => ({
theme: state.theme,
locale: state.locale,
}),
}
),
{ name: "AppStore" }
)
);
スライスpatternで大規模ストアを分割
大規模applicationでは、ストアをスライスに分割してmanagementし है।
// userSlice.ts
interface UserSlice {
user: User | null;
isAuthenticated: boolean;
login: (credentials: LoginCredentials) => Promise<void>;
logout: () => void;
}
const createUserSlice: StateCreator<StoreState, [], [], UserSlice> = (set) => ({
user: null,
isAuthenticated: false,
login: async (credentials) => {
const user = await authApi.login(credentials);
set({ user, isAuthenticated: true });
},
logout: () => set({ user: null, isAuthenticated: false }),
});
// uiSlice.ts
interface UISlice {
sidebarOpen: boolean;
modalStack: string[];
toggleSidebar: () => void;
openModal: (id: string) => void;
closeModal: () => void;
}
const createUISlice: StateCreator<StoreState, [], [], UISlice> = (set) => ({
sidebarOpen: true,
modalStack: [],
toggleSidebar: () => set((s) => ({ sidebarOpen: !s.sidebarOpen })),
openModal: (id) => set((s) => ({ modalStack: [...s.modalStack, id] })),
closeModal: () => set((s) => ({ modalStack: s.modalStack.slice(0, -1) })),
});
// store.ts - スライスをintegration
type StoreState = UserSlice & UISlice;
export const useStore = create<StoreState>()((...a) => ({
...createUserSlice(...a),
...createUISlice(...a),
}));
セレクターによるperformanceoptimization
不要な再レンダリングを防ぐके लिए、セレクター use करके分け है।
// 個別の値 fetch(推奨)
function CartIcon() {
const totalItems = useCartStore((state) => state.totalItems());
return <span>cart ({totalItems})</span>;
}
// shallow比較でオブジェクト fetch
import { useShallow } from "zustand/react/shallow";
function CartSummary() {
const { totalItems, totalPrice } = useCartStore(
useShallow((state) => ({
totalItems: state.totalItems(),
totalPrice: state.totalPrice(),
}))
);
return (
<div>
<p>{totalItems}点の商品</p>
<p>合計: ¥{totalPrice.toLocaleString()}</p>
</div>
);
}
Summary
Zustandはउसシンプルさとflexible性で、多くのReactProjectの状態managementに適してい है।Claude Code का उपयोग करके、ストア設計 सेmiddleware構成、performanceoptimization तक一貫して素早くimplementationでき है।
アトミックな状態managementのアプローチはJotaiアトミック状態managementを、datafetchとのintegrationはTanStack Queryutilizationガイドをदेखें。Zustandofficial documentationもconfirmしておきましょう。
Related Posts
Claude Code से अपने Side Projects को Supercharge कैसे करें [Examples के साथ]
Claude Code से personal development projects को dramatically speed up करना सीखें। Real-world examples और idea से deployment तक practical workflow शामिल है।
Claude Code से Refactoring कैसे Automate करें
Claude Code से efficiently code refactoring automate करना सीखें। Real-world projects के लिए practical prompts और concrete refactoring patterns शामिल हैं।
Claude Code के साथ Complete CORS Configuration Guide
Claude Code का उपयोग करके complete CORS configuration guide सीखें। Practical tips और code examples शामिल हैं।