State Management in React Native
State management is crucial for building interactive apps. React Native offers several approaches, from simple component state to global state management solutions.
State Management Options
βββββββββββββββββββββββββββββββββββββββββββββββββββ
β State Management Hierarchy β
βββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Simple βββββββββββββββββββββββββββ Complex β
β β
β useState Context API Redux Zustand β
β (local) (shared) (global) (global) β
β β
β ββββββββββ ββββββββββββββ ββββββββββββββββ β
β βComponentβ β Provider β β Store β β
β β State β β Context β β Reducers β β
β ββββββββββ ββββββββββββββ ββββββββββββββββ β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββ
Using useState for Local State
import React, { useState } from 'react';
import { View, Text, TextInput, Button } from 'react-native';
const Counter = () => {
const [count, setCount] = useState(0);
const [name, setName] = useState('');
return (
<View style={{ padding: 20 }}>
<TextInput
placeholder="Enter your name"
value={name}
onChangeText={setName}
style={{ borderWidth: 1, padding: 10, marginBottom: 10 }}
/>
<Text style={{ fontSize: 24 }}>Hello, {name || 'World'}!</Text>
<Text style={{ fontSize: 24, marginTop: 20 }}>Count: {count}</Text>
<Button title="Increment" onPress={() => setCount(count + 1)} />
<Button title="Decrement" onPress={() => setCount(count - 1)} />
</View>
);
};
Context API for Shared State
import React, { createContext, useContext, useState } from 'react';
const ThemeContext = createContext();
const ThemeProvider = ({ children }) => {
const [isDark, setIsDark] = useState(false);
const toggleTheme = () => setIsDark(!isDark);
return (
<ThemeContext.Provider value={{ isDark, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
const ThemedButton = () => {
const { isDark, toggleTheme } = useContext(ThemeContext);
return (
<Button
title={isDark ? 'Light Mode' : 'Dark Mode'}
onPress={toggleTheme}
/>
);
};
When to Use What?
- useState: For component-specific state (form inputs, toggles)
- Context API: For shared state across a few components (theme, auth)
- Redux/Zustand: For complex global state with many updates