How to use Zustand in React Native:
-
Install Zustand
bashnpm install zustand # or yarn add zustand -
Create Store
javascriptimport { create } from 'zustand'; const useCounterStore = create((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })), decrement: () => set((state) => ({ count: state.count - 1 })), })); -
Use in React Native components
javascriptimport React from 'react'; import { View, Text, TouchableOpacity, StyleSheet } from 'react-native'; import { useCounterStore } from './store'; export default function CounterScreen() { const count = useCounterStore((state) => state.count); const increment = useCounterStore((state) => state.increment); const decrement = useCounterStore((state) => state.decrement); return ( <View style={styles.container}> <Text style={styles.count}>{count}</Text> <View style={styles.buttons}> <TouchableOpacity style={styles.button} onPress={decrement}> <Text style={styles.buttonText}>-</Text> </TouchableOpacity> <TouchableOpacity style={styles.button} onPress={increment}> <Text style={styles.buttonText}>+</Text> </TouchableOpacity> </View> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, count: { fontSize: 48, marginBottom: 20, }, buttons: { flexDirection: 'row', gap: 20, }, button: { backgroundColor: '#007AFF', padding: 15, borderRadius: 8, }, buttonText: { color: 'white', fontSize: 24, fontWeight: 'bold', }, }); -
Persistent state
- Use persist middleware to save state to AsyncStorage
- Example:
javascript
import { create } from 'zustand'; import { persist } from 'zustand/middleware'; import AsyncStorage from '@react-native-async-storage/async-storage'; const useUserStore = create( persist( (set) => ({ user: null, setUser: (user) => set({ user }), }), { name: 'user-storage', storage: { getItem: async (name) => { const item = await AsyncStorage.getItem(name); return item ? JSON.parse(item) : null; }, setItem: async (name, value) => { await AsyncStorage.setItem(name, JSON.stringify(value)); }, removeItem: async (name) => { await AsyncStorage.removeItem(name); }, }, } ) );
-
React Native specific optimizations
- Avoid complex calculations in selectors
- Properly use useCallback to cache callback functions
- Be mindful of AsyncStorage performance impact
-
Common use cases
- User authentication state management
- App settings and preferences
- Shopping cart state
- Navigation state management