Skip to main content

Lesson 3 of 9

Zustand - Global State with Slices

Zustand is a tiny state management library that works with or without React, has zero boilerplate, and supports selectors that prevent unnecessary re-renders. In React Native it also integrates with AsyncStorage for persistence via the persist middleware.

30 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Installation

Installation
npm install zustand
npm install @react-native-async-storage/async-storage

Cart Store with Persistence

Cart Store with Persistence
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';

interface CartItem { id: string; name: string; price: number; quantity: number; imageUri: string; }

interface CartStore {
  items: CartItem[];
  addItem: (item: Omit<CartItem, 'quantity'>) => void;
  removeItem: (id: string) => void;
  incrementQty: (id: string) => void;
  decrementQty: (id: string) => void;
  clearCart: () => void;
  // Derived values as actions (computed inline)
  itemCount: () => number;
  totalPrice: () => number;
}

export const useCartStore = create<CartStore>()(
  persist(
    (set, get) => ({
      items: [],

      addItem: (product) => set(state => {
        const existing = state.items.find(i => i.id === product.id);
        if (existing) {
          return { items: state.items.map(i => i.id === product.id ? { ...i, quantity: i.quantity + 1 } : i) };
        }
        return { items: [...state.items, { ...product, quantity: 1 }] };
      }),

      removeItem: (id) => set(state => ({ items: state.items.filter(i => i.id !== id) })),

      incrementQty: (id) => set(state => ({
        items: state.items.map(i => i.id === id ? { ...i, quantity: i.quantity + 1 } : i),
      })),

      decrementQty: (id) => set(state => ({
        items: state.items
          .map(i => i.id === id ? { ...i, quantity: i.quantity - 1 } : i)
          .filter(i => i.quantity > 0),  // remove if quantity hits 0
      })),

      clearCart: () => set({ items: [] }),

      itemCount: () => get().items.reduce((sum, i) => sum + i.quantity, 0),
      totalPrice: () => get().items.reduce((sum, i) => sum + i.price * i.quantity, 0),
    }),
    {
      name: 'cart-storage',                            // AsyncStorage key
      storage: createJSONStorage(() => AsyncStorage),  // persist to AsyncStorage
      // Partial persistence - only persist the items array, not derived methods
      partialize: (state) => ({ items: state.items }),
    }
  )
);

// ---- Usage with selectors (prevent re-renders) ----
// โœ… Only re-renders when itemCount changes
function CartBadge() {
  const count = useCartStore(state => state.itemCount());
  return <Text style={{ color: 'white', fontSize: 11 }}>{count}</Text>;
}

// โœ… Only re-renders when items changes
function CartScreen() {
  const items = useCartStore(state => state.items);
  const total = useCartStore(state => state.totalPrice());
  const removeItem = useCartStore(state => state.removeItem);

  return (
    <FlatList
      data={items}
      keyExtractor={i => i.id}
      renderItem={({ item }) => (
        <View style={{ flexDirection: 'row', alignItems: 'center', padding: 16 }}>
          <Text style={{ flex: 1, color: '#f1f5f9' }}>{item.name} ร— {item.quantity}</Text>
          <Text style={{ color: '#94a3b8' }}>${(item.price * item.quantity).toFixed(2)}</Text>
          <Pressable onPress={() => removeItem(item.id)} style={{ marginLeft: 12 }}>
            <Text>๐Ÿ—‘</Text>
          </Pressable>
        </View>
      )}
      ListFooterComponent={
        <Text style={{ padding: 16, fontWeight: '700', color: '#f1f5f9', fontSize: 18 }}>
          Total: ${total.toFixed(2)}
        </Text>
      }
    />
  );
}

// ---- Accessing store OUTSIDE React (e.g., in axios interceptor) ----
function getAuthToken() {
  return useCartStore.getState().items; // direct state access without hook
}

Tip

Tip

Practice Zustand Global State with Slices in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Creating modular Zustand stores with atomic selectors for high performance

Practice Task

Note

Practice Task - (1) Write a working example of Zustand Global State with Slices from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Zustand Global State with Slices is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.

Topics in This Module

0/9 done