set(), and Selectors
Ek nazar me Zustand ka basic syntax, store banana, data padhna (Selectors) aur data badalna (Actions).
1. Store Banao: const useStore = create((set) => ({ ... }))
2. Data Padho: const data = useStore((s) => s.data)
3. Data Badlo: const action = useStore((s) => s.action)
| Zustand Code Snippet | Iska Matlab & Kaam |
|---|---|
import { create } from "zustand" |
Store factory tool import kiya (Koi <Provider> nahi chahiye). |
create<MyStore>()((set) => ({ ... })) |
TypeScript ke sath store banane ka standard syntax. |
set((state) => ({ count: state.count + 1 })) |
Purani value (state) ke hisaab se nayi value update ki. |
set({ count: 0 }) |
Direct nayi value set ki (partial merge). |
meals: [newItem, ...state.meals] |
Array ke shuruat me naya item joda (Immutable spread). |
| Selector Code | Kab Aur Kyun Use Karein? |
|---|---|
useMealStore((s) => s.meals) |
Jab screen me poori meals list dikhani ho (e.g. Today screen). |
useMealStore((s) => s.addMeal) |
Jab button click par naya meal add karna ho (Action reference). |
useMealStore((s) => s.meals.length) |
Jab sirf count chahiye ho (e.g. Tab badge). |
useMealStore((s) => s.meals.reduce(...)) |
Jab derived total chahiye ho (e.g. Total Calories in Analytics). |
useState) vs Global Store (Zustand)| Data Ka Type | Sahi Jagah (Kahan Rakhna Chahiye?) |
|---|---|
| Logged Meals, Total Calories, Tab Badge | Zustand Store (Kyunki sabhi screens ko chahiye) |
| Form Input Draft (User jab name/calories type kar raha ho) | Local useState (Kyunki sirf wahi screen type kar rahi hai) |
| Form Error Message ("Please enter meal name") | Local useState |
| File Path | Role in MacroZone App |
|---|---|
store/useMealStore.ts |
Central Single Source of Truth (All meals & add/remove actions). |
app/(tabs)/index.tsx |
Today screen — shows list of meals & quick log button. |
app/add-meal.tsx |
Modal screen — user types meal and calls addMeal. |
app/(tabs)/analytics.tsx |
Analytics screen — calculates total calories & protein bars. |
app/(tabs)/_layout.tsx |
Bottom tab layout — shows live meal count badge on tab. |