State Management with Zustand
Lightweight, hooks-based state management for React Native and Next.js
A lightweight, hooks-based state management library that simplifies global state for auth (user data), e-commerce (cart), and social media (feeds). Supports TypeScript and persistence via AsyncStorage for React Native, ensuring state persists across app restarts.
Chosen over Redux for minimal boilerplate and over Jotai for simpler store-based management, aligning with starter kit goals. Perfect for managing cart state, user sessions, and app-wide settings.
- Minimal Boilerplate
Less code compared to Redux or Context API
- TypeScript Ready
Excellent TypeScript support out of the box
- Hooks-Based
Natural React hooks API
- AsyncStorage Support
Persist state across app restarts
- Small Bundle Size
Lightweight for mobile applications
- Performance
Optimized for React Native performance
- • User session data
- • Authentication tokens
- • User preferences
- • Profile information
- • Shopping cart state
- • Wishlist items
- • Order history
- • Product filters
- • Feed state
- • Notification count
- • Theme preferences
- • App settings
Installation
npm install zustand
Cart Store Example
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
interface CartItem {
id: string
name: string
price: number
quantity: number
}
interface CartStore {
items: CartItem[]
addItem: (item: CartItem) => void
removeItem: (id: string) => void
clearCart: () => void
total: number
}
export const useCartStore = create<CartStore>()(
persist(
(set, get) => ({
items: [],
addItem: (item) => set((state) => ({
items: [...state.items, item]
})),
removeItem: (id) => set((state) => ({
items: state.items.filter(item => item.id !== id)
})),
clearCart: () => set({ items: [] }),
get total() {
return get().items.reduce((sum, item) =>
sum + item.price * item.quantity, 0
)
}
}),
{ name: 'cart-storage' }
)
)
Using the Store
import { useCartStore } from './stores/cartStore'
export function CartComponent() {
const { items, addItem, total } = useCartStore()
return (
<View>
<Text>Items: {items.length}</Text>
<Text>Total: 100</Text>
</View>
)
}