State Management
Complete guide to global state management using Zustand selectors in Caracal.
Caracal uses Zustand for global client state management, combined with React Query for server state. This guide covers Zustand selectors and MMKV persistence integration.
Overview
Caracal follows a clear separation of concerns for state management:
- Zustand: Global client state (auth, user preferences, UI state)
- React Query: Server state (API data, caching, synchronization)
- MMKV: Persistent storage (session, settings, cached data)
Why This Approach?
- Simple: Minimal boilerplate, no context providers needed
- Performant: Selector pattern prevents unnecessary re-renders
- Type-safe: Full TypeScript support with inference
- Persistent: Easy integration with MMKV storage
- Testable: Simple store access without complex setup
Why Zustand?
Zustand is a small (1KB), fast, and scalable state management solution that doesn't require wrapping your app in context providers.
Advantages over alternatives:
| Feature | Zustand | Redux | Context API | Jotai |
|---|---|---|---|---|
| Bundle size | 1KB | 8KB+ | 0KB | 3KB |
| Boilerplate | Minimal | Heavy | Medium | Minimal |
| Performance | Excellent | Excellent | Poor | Excellent |
| DevTools | Yes | Yes | No | Yes |
| Persistence | Easy | Medium | Hard | Easy |
| TypeScript | Excellent | Good | Good | Excellent |
The Selectors Pattern
Caracal uses Zustand's native selector API to optimize component re-renders. Instead of subscribing to the entire store, components subscribe only to the specific state slices they need.
How It Works
Pass a selector function directly to the store hook. Zustand subscribes the component to that selected value.
Without selectors (inefficient):
// ❌ Component re-renders on ANY state change
const { userId, status, signIn, signOut } = useAuth();
// Only using userId, but re-renders when status changes too
return <Text>{userId}</Text>;With selectors (optimized):
// ✅ Component re-renders ONLY when userId changes
const userId = useAuth((state) => state.userId);
return <Text>{userId}</Text>;Performance Impact
// Example: 3 components using auth state
// Component A: Only needs userId
const userId = useAuth((state) => state.userId); // Re-renders only when userId changes
// Component B: Only needs status
const status = useAuth((state) => state.status); // Re-renders only when status changes
// Component C: Only needs signOut function
const signOut = useAuth((state) => state.signOut); // Never re-renders (functions are stable)Without selectors, all 3 components would re-render on every state change. With selectors, each component re-renders only when its specific data changes.
Zustand 5 Selector Rules
Zustand 5 compares selector results with Object.is. Prefer one primitive, object reference, or action per selector because it gives React the smallest possible subscription and naturally returns a stable value.
When a component needs several fields, separate selectors are the simplest default:
const userId = useAuth((state) => state.userId);
const status = useAuth((state) => state.status);If grouping fields makes the component clearer, wrap the selector with useShallow. Without it, a new object or array is created on every call; in Zustand 5 that can cause unnecessary renders or a Maximum update depth exceeded loop.
import { useShallow } from 'zustand/react/shallow';
const { userId, status } = useAuth(
useShallow((state) => ({
userId: state.userId,
status: state.status,
}))
);Derive simple values in selectors instead of duplicating them in the store:
const isSignedIn = useAuth(
(state) => state.status === 'signIn' && state.userId !== null
);Never return a fresh object, array, or fallback function from a selector unless you stabilize it. Use separate selectors, useShallow, or a constant declared outside the component.
Auth Store Example
Caracal includes a production-ready authentication store (src/lib/auth/store.ts) demonstrating all key patterns.
The auth store in src/lib/auth/store.ts exposes status, userId, signIn(userId), signOut() and hydrate(). The sign-in form calls loginWithEmail to verify credentials before updating the store. Hydration checks that the saved session points to an existing account. See Authentication.
Using the Auth Store
const userId = useAuth((state) => state.userId);
const signOut = useAuth((state) => state.signOut);Outside components:
import { signOut } from '@/lib/auth';
// In API interceptor
axios.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
signOut(); // Trigger sign out from anywhere
}
return Promise.reject(error);
}
);MMKV Persistence
The starter persists its session and preferences in MMKV. The instance in src/lib/storage.tsx uses createMMKV() with no encryption key. See the storage guide for the keys and their owners.
Persisting Store State
Manual persistence (used in auth):
import { getItem, setItem } from '@/lib/storage';
const useStore = create<State>()((set) => ({
data: null,
setData: (data) => {
setItem('my-data', data); // Save to MMKV
set({ data }); // Update state
},
hydrate: () => {
const data = getItem('my-data'); // Load from MMKV
if (data) set({ data });
},
}));Automatic persistence with middleware:
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { storage } from '@/lib/storage';
type State = {
theme: 'light' | 'dark';
setTheme: (theme: 'light' | 'dark') => void;
};
export const useSettings = create<State>()(
persist(
(set) => ({
theme: 'light',
setTheme: (theme) => set({ theme }),
}),
{
name: 'settings-storage',
storage: createJSONStorage(() => ({
getItem: (key) => storage.getString(key) ?? null,
setItem: (key, value) => {
storage.set(key, value);
},
removeItem: (key) => {
storage.remove(key);
},
})),
}
)
);Creating Custom Stores
Follow this pattern to create new Zustand stores in Caracal.
1. Define Types
// src/lib/preferences/types.ts
export type Theme = 'light' | 'dark' | 'system';
export type Language = 'en' | 'es' | 'fr';
export interface PreferencesState {
theme: Theme;
language: Language;
notifications: boolean;
setTheme: (theme: Theme) => void;
setLanguage: (language: Language) => void;
toggleNotifications: () => void;
reset: () => void;
}2. Create Store
// src/lib/preferences/index.tsx
import { create } from 'zustand';
import { getItem, setItem, removeItem } from '@/lib/storage';
import type { PreferencesState, Theme, Language } from './types';
const STORAGE_KEY = 'preferences';
const initialState = {
theme: 'system' as Theme,
language: 'en' as Language,
notifications: true,
};
export const usePreferences = create<PreferencesState>()((set, get) => ({
...initialState,
setTheme: (theme) => {
const state = get();
const newState = { ...state, theme };
setItem(STORAGE_KEY, newState);
set({ theme });
},
setLanguage: (language) => {
const state = get();
const newState = { ...state, language };
setItem(STORAGE_KEY, newState);
set({ language });
},
toggleNotifications: () => {
const state = get();
const notifications = !state.notifications;
const newState = { ...state, notifications };
setItem(STORAGE_KEY, newState);
set({ notifications });
},
reset: () => {
removeItem(STORAGE_KEY);
set(initialState);
},
}));
// Hydrate from storage on app start
const stored = getItem<PreferencesState>(STORAGE_KEY);
if (stored) {
usePreferences.setState(stored);
}
// Export actions for use outside components
export const setTheme = (theme: Theme) =>
usePreferences.getState().setTheme(theme);
export const setLanguage = (language: Language) =>
usePreferences.getState().setLanguage(language);
export const resetPreferences = () =>
usePreferences.getState().reset();3. Use in Components
import { usePreferences } from '@/lib/preferences';
export function SettingsScreen() {
const theme = usePreferences((state) => state.theme);
const language = usePreferences((state) => state.language);
const setTheme = usePreferences((state) => state.setTheme);
const setLanguage = usePreferences((state) => state.setLanguage);
return (
<View>
<Select value={theme} onValueChange={setTheme}>
<SelectItem value="light">Light</SelectItem>
<SelectItem value="dark">Dark</SelectItem>
<SelectItem value="system">System</SelectItem>
</Select>
<Select value={language} onValueChange={setLanguage}>
<SelectItem value="en">English</SelectItem>
<SelectItem value="es">Español</SelectItem>
<SelectItem value="fr">Français</SelectItem>
</Select>
</View>
);
}Zustand vs React Query
Understanding when to use each tool is crucial for maintainable architecture.
Use Zustand For:
Client-only state:
- Authentication status
- User preferences (theme, language)
- UI state (modal open/closed, selected tab)
- Form state across multiple screens
- App-wide flags (feature flags, onboarding completed)
// ✅ Good: Client state in Zustand
const useUIStore = create((set) => ({
isModalOpen: false,
selectedTab: 'home',
openModal: () => set({ isModalOpen: true }),
closeModal: () => set({ isModalOpen: false }),
}));Use React Query For:
Server state:
- API data (posts, users, products)
- Remote data fetching
- Caching and synchronization
- Background updates
- Optimistic updates
- Invalidation and refetching
// ✅ Good: Server state in React Query
import { createQuery } from 'react-query-kit';
export const useUser = createQuery({
queryKey: ['user'],
fetcher: () => axios.get('/api/user'),
});
// Usage
const { data: user, isLoading } = useUser();Don't Mix Them
// ❌ Bad: Storing API data in Zustand
const useStore = create((set) => ({
users: [],
fetchUsers: async () => {
const users = await api.getUsers();
set({ users });
},
}));
// ❌ Bad: Storing UI state in React Query
const { data: isModalOpen } = useQuery(['modal'], () => false);Advanced Patterns
1. Derived Selectors
interface CartState {
items: CartItem[];
addItem: (item: CartItem) => void;
removeItem: (id: string) => void;
}
export const useCart = create<CartState>()((set) => ({
items: [],
addItem: (item) =>
set((state) => ({ items: [...state.items, item] })),
removeItem: (id) =>
set((state) => ({
items: state.items.filter((item) => item.id !== id),
})),
}));
const selectTotal = (state: CartState) =>
state.items.reduce((sum, item) => sum + item.price, 0);
const total = useCart(selectTotal);Selectors keep derived values synchronized without storing duplicate state. Define expensive reusable selectors outside components so the selector function itself is stable.
2. Middleware for Logging
import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
const _useStore = create<State>()(
devtools(
(set) => ({
// your store
}),
{ name: 'MyStore' }
)
);Install Redux DevTools to inspect state changes in development.
3. Resetting Store
const initialState = {
count: 0,
text: '',
};
const _useStore = create<State>()((set) => ({
...initialState,
increment: () => set((state) => ({ count: state.count + 1 })),
setText: (text) => set({ text }),
reset: () => set(initialState),
}));4. Async Actions
const _useStore = create<State>()((set) => ({
data: null,
loading: false,
error: null,
fetchData: async () => {
set({ loading: true, error: null });
try {
const response = await api.getData();
set({ data: response, loading: false });
} catch (error) {
set({ error: error.message, loading: false });
}
},
}));While Zustand can handle async actions, React Query is better suited for server state. Use Zustand async actions only for client-side operations (e.g., uploading files, processing images).
5. Subscribing to Changes
Use subscribeWithSelector for selective subscriptions outside React. This is useful for high-frequency events, analytics, or imperative integrations that should not re-render a component.
import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
interface PositionState {
x: number;
setX: (x: number) => void;
}
const usePosition = create<PositionState>()(
subscribeWithSelector((set) => ({
x: 0,
setX: (x) => set({ x }),
}))
);
const unsubscribe = usePosition.subscribe(
(state) => state.x,
(x) => {
updateNativeView(x);
}
);
// Call when the integration is disposed.
unsubscribe();For React UI, keep using the store hook with a selector. Subscriptions are an escape hatch, not a replacement for reactive rendering.
Best Practices
1. Keep Stores Focused
// ✅ Good: Single responsibility
const useAuth = create(...); // Auth only
const useTheme = create(...); // Theme only
const usePrefs = create(...); // Preferences only
// ❌ Bad: God store
const useGlobalStore = create(...); // Everything in one store2. Use Focused Selectors
// ✅ Good: Selective subscriptions
const userId = useAuth((state) => state.userId);
const status = useAuth((state) => state.status);
// ❌ Bad: Full store subscription
const { userId, status, signIn, signOut } = useAuth();Performance checklist:
- Select only values the component renders.
- Prefer separate selectors for unrelated fields.
- Use
useShallowwhen returning an object or array of multiple fields. - Keep selector outputs stable; do not create fallback functions inline.
- Derive values in selectors instead of storing synchronized duplicates.
- Use
getState()only outside render logic where no reactive subscription is needed. - Use
subscribeWithSelectoronly for high-frequency imperative work.
3. Export Actions
// ✅ Good: Actions available outside components
export const signOut = () => useAuth.getState().signOut();
// Usage in API interceptor
if (error.status === 401) {
signOut();
}4. Type Everything
// ✅ Good: Explicit types
interface State {
count: number;
increment: () => void;
}
const useStore = create<State>()((set) => ({
count: 0,
increment: () => set((s) => ({ count: s.count + 1 })),
}));Persistence and startup
The local demo stores a user ID in the session. If you add a backend, choose storage for its credentials separately. The root layout calls hydrateAuth() at module scope before evaluating the route guards.
Testing Stores
Zustand stores are easy to test without complex setup.
// preferences.test.tsx
import { renderHook, act } from '@testing-library/react-native';
import { usePreferences, resetPreferences } from '@/lib/preferences';
describe('Preferences Store', () => {
beforeEach(() => {
resetPreferences(); // Reset to initial state
});
it('should set theme', async () => {
const { result } = await renderHook(() =>
usePreferences((state) => state.setTheme)
);
await act(() => {
result.current('dark');
});
const { result: themeResult } = await renderHook(() =>
usePreferences((state) => state.theme)
);
expect(themeResult.current).toBe('dark');
});
it('should toggle notifications', async () => {
const { result: toggle } = await renderHook(() =>
usePreferences((state) => state.toggleNotifications)
);
const { result: notifications } = await renderHook(() =>
usePreferences((state) => state.notifications)
);
expect(notifications.current).toBe(true); // initial
await act(() => {
toggle.current();
});
expect(notifications.current).toBe(false); // toggled
});
});Troubleshooting
Store Updates Not Triggering Re-renders
// ✅ Correct
const userId = useAuth((state) => state.userId);
// ❌ Wrong: accessing property directly — no subscription
const userId = useAuth.getState().userId;Re-rendering Too Often
// ❌ Bad: subscribes to entire store
const store = useAuth();
// ✅ Good: subscribes only to userId
const userId = useAuth((state) => state.userId);Persisted State Not Loading
Call hydration in the root layout:
// src/app/_layout.tsx
useEffect(() => {
hydrateAuth();
// ... other hydrations
}, []);TypeScript Errors with Selectors
const useStore = create<State>()(...);
const value = useStore((state) => state.value);Actions Not Updating State
// ✅ Correct
increment: () => set((state) => ({ count: state.count + 1 }))
// ❌ Wrong: mutating state directly
increment: () => {
get().count++; // Doesn't trigger re-render!
}Additional Resources
- Zustand Documentation
- Prevent re-renders with
useShallow - Zustand 5 migration guide
- Zustand TypeScript guide
- Zustand DevTools
- MMKV Documentation
- React Query Documentation
- Data Fetching Guide
- Storage Guide
Summary
- Use Zustand for client state, React Query for server state
- Use focused, stable selector functions for performance
- Use
useShallowwhen one selector returns multiple fields - Derive values with selectors instead of duplicating state
- Persist important state with MMKV integration
- Export actions for use outside components (API interceptors, utils)
- Keep stores focused — single responsibility principle
- Hydrate on app start to restore persisted state
- Type everything for safety and autocomplete
The auth store (src/lib/auth/store.ts) serves as a complete example demonstrating all these patterns in production.