State Management
Guide for implementing state management in your AppCatalyst RN application using Zustand.
Add New Persistent State
To add a new persistent state to the app, you need to modify both the useApp and useCache stores.
📐 Type Definition (state/types/app.types.ts)
Define the type for the new persistent state object, OnboardingState.
state/types/app.types.ts
// ... other types ...
export type OnboardingState = {
isSeen: boolean | null;
setIsSeen: (isSeen: boolean) => void;
};
// ... other types ...💾 Persistent State (useApp Store)
The persistent state is managed by the main useApp store, which uses the persist middleware with react-native-mmkv. I’ve added the new onboarding logic here.
state/app.ts
// ... imports (create, persist, createJSONStorage, storage, AppState) ...
// ... createMMKVStorage utility definition ...
export const useApp = create<AppState>()(
persist(
(set) => {
// Add your new persistence values here
return {
onboarding: {
isSeen: false,
setIsSeen: (isSeen: boolean) =>
set((state) => ({ onboarding: { ...state.onboarding, isSeen } })),
},
// ... potentially other persistent state branches ...
};
},
{
name: 'app-storage',
storage: createJSONStorage(() => storage), // Using MMKV storage
// ... whitelist/blacklist config ...
}
)
);⏰ Cache State (useCache Store)
The temporary state that should not persist across app launches is managed by useCache. This includes the new isLoading and guest states.
state/cache.ts
import { create } from 'zustand';
// Assuming CacheState is defined as:
// export type CacheState = {
// isLoading: boolean;
// setIsLoading: (isLoading: boolean) => void;
// guest: boolean;
// setGuest: (guest: boolean) => void;
// };
import { CacheState } from './types/app.types';
export const useCache = create<CacheState>((set) => ({
isLoading: true,
setIsLoading: (isLoading: boolean) => set({ isLoading }),
guest: false,
setGuest: (guest: boolean) => set({ guest }),
// Add new cache values here if needed
}));