State Management and Data Flow
12 min read
Course: Expo
Topic: State Management and Data Flow
Welcome to the central nervous system of your Expo application. If UI components are the bones and skin of your app, State is the brain, the memories, and the blood pumping through it. Without state, your app is just a pretty painting. With state, it becomes a living, breathing application.
In this guide, we will break down how to store memory in your app, how to pass it around efficiently, how to gather input from users without crying over validation logic, and how to manage data on a global scale.
1. Local State Mastery: useState and useEffect
The Problem
Imagine you declare a normal JavaScript variable let count = 0;, display it in your app, and then run a function that changes it to count = 1;. The variable updates in the device's memory, but your screen still shows 0. Why? Because the UI has no idea the data changed. It does not automatically "watch" variables.
Definition: useState
useState is a React Hook that lets you add a state variable to your component. When a state variable is updated using its designated setter function, it tells React to re-render the component and update the screen with the new value.
Real-Life Scenario: The Digital Scoreboard
Imagine you are operating a digital scoreboard at a basketball game. If you write the score on a piece of paper in your pocket (a normal variable), the players and the crowd (the UI) cannot see it. useState is the big red button on your desk. When you press the button (the setter function), the giant digital board in the arena instantly updates so everyone can see the new score.
How it works in practice
Industry standard dictates we use useState for highly localized data: toggling a modal, tracking a counter, or holding the current tab index.
import React, { useState } from 'react';
import { View, Text, Pressable, StyleSheet } from 'react-native';
export default function CounterApp() {
// Definition: [currentValue, functionToUpdateValue] = useState(initialValue)
const [count, setCount] = useState(0);
return (
<View style={styles.container}>
<Text style={styles.text}>Current Score: {count}</Text>
{/*
Under the hood: calling setCount schedules a re-render.
React queues this update and repaints the screen.
*/}
<Pressable
style={styles.button}
onPress={() => setCount(count + 1)}
>
<Text style={styles.buttonText}>Add Point</Text>
</Pressable>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
text: { fontSize: 24, marginBottom: 20 },
button: { backgroundColor: '#007AFF', padding: 15, borderRadius: 8 },
buttonText: { color: 'white', fontWeight: 'bold' }
});The Problem with Side Effects
Sometimes your component needs to do things outside of simply returning UI elements. It needs to fetch data from a server, start a timer, or read from the device's local storage. If you put a network request directly inside your component, it will run every single time the component re-renders. If a user types 10 characters into an input field, you just sent 10 identical network requests and likely crashed your backend.
Definition: useEffect
useEffect is a React Hook that lets you synchronize a component with an external system. It allows you to execute side effects after the component renders, controlled by an array of dependencies.
Real-Life Scenario: The Mail Room
Imagine you are managing an office (the component). Every time an employee moves a chair (a re-render), you do not need to check the mailbox outside. You only want to check the mailbox once when the office opens in the morning (on mount), and maybe again only if the delivery truck arrives (a specific dependency changing). useEffect is your instructions to the mail clerk on when to go outside.
How it works in practice
The dependency array is the most important part of useEffect.
[](Empty array): Run exactly once when the component mounts.[variable]: Run on mount, AND whenevervariablechanges.- (No array): Run on every single render. (Danger: Rarely used, leads to infinite loop explosions).
import React, { useState, useEffect } from 'react';
import { View, Text, ActivityIndicator } from 'react-native';
export default function UserProfile() {
const [userData, setUserData] = useState(null);
const [loading, setLoading] = useState(true);
// This effect runs ONLY ONCE when the component first appears
useEffect(() => {
async function fetchUser() {
try {
// Simulating a network request
const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
const data = await response.json();
setUserData(data);
} catch (error) {
console.error("Failed to fetch user");
} finally {
setLoading(false);
}
}
fetchUser();
// The cleanup function (optional) runs when the component unmounts
return () => {
console.log("Component destroyed, cleaning up...");
};
}, []); // <-- Empty array means "fire once on mount"
if (loading) return <ActivityIndicator size="large" />;
return (
<View style={{ padding: 40 }}>
<Text>Name: {userData?.name}</Text>
<Text>Email: {userData?.email}</Text>
</View>
);
}2. Prop Drilling and Context API: Sharing Data Across Screens
The Problem: Prop Drilling
You have a deeply nested app. The App component holds the user's login status, but the Avatar component (which is 15 layers deep inside Header -> Navigation -> ProfileContainer -> UserBox -> Avatar) needs it. Passing isLoggedIn={isLoggedIn} through 14 intermediate components that do not care about this data is called "Prop Drilling." It makes your code ugly, rigid, and a nightmare to refactor.
Definition: Context API
The Context API is a built-in React feature that provides a way to pass data through the component tree without having to pass props down manually at every level. It consists of a Provider (which supplies the data) and a Consumer or useContext hook (which reads the data).
Real-Life Scenario: The Airport PA System
Imagine an airport. A gate change occurs for Flight 101. Prop drilling is the gate agent whispering the gate change to a janitor, who whispers it to a barista, who whispers it to a security guard, who finally tells the passenger. It is terribly inefficient.
The Context API is the Airport PA System. The gate agent speaks into the microphone (the Provider). The message echoes throughout the entire airport. Only the passengers of Flight 101 (the Consumers) actually listen and react to it; everyone else ignores it.
How it works in practice
Industry standard usage for Context API includes Theme (Light/Dark mode), Authentication state, and Localization (Language settings). Note: We do not use Context for data that changes rapidly (like a scrolling position), because whenever the Provider's value changes, EVERY component listening to it re-renders.
import React, { createContext, useContext, useState } from 'react';
import { View, Text, Pressable } from 'react-native';
// 1. Create the Context
const ThemeContext = createContext('light');
// 2. Create a Provider Component
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme(prev => prev === 'light' ? 'dark' : 'light');
};
return (
// Everything wrapped inside this will have access to 'theme' and 'toggleTheme'
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
}
// 3. Consume the Context deeper in the tree
function ThemedButton() {
// No props needed! We just plug into the PA system.
const { theme, toggleTheme } = useContext(ThemeContext);
const isDark = theme === 'dark';
return (
<Pressable
onPress={toggleTheme}
style={{ backgroundColor: isDark ? '#333' : '#ddd', padding: 20 }}
>
<Text style={{ color: isDark ? '#fff' : '#000' }}>
Current Theme: {theme} (Tap to change)
</Text>
</Pressable>
);
}
// Usage in App
export default function App() {
return (
<ThemeProvider>
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<ThemedButton />
</View>
</ThemeProvider>
);
}3. Form Handling and Validation Essentials
The Problem
Building forms natively in React is exhausting. You have to create a state variable for every single input field, write custom logic for error validation (e.g., "Is this a valid email?"), handle the submission logic, and manage loading states. If you have 10 fields, your component will re-render every time the user types a single keystroke, slowing down older mobile devices.
Definition: React Hook Form & Zod
- React Hook Form (RHF): A library that manages form state using uncontrolled components. It minimizes re-renders and handles form submission and errors efficiently.
- Zod: A schema declaration and validation library. It allows you to strictly define the shape and rules of your data.
Real-Life Scenario: The Bouncer and the Clipboard
Imagine trying to enter an ultra-exclusive club.
Native React forms are like the bouncer stopping you after every single step you take toward the door to ask your name, age, and ID. It is exhausting (re-renders).
React Hook Form is the clipboard. You write all your details down peacefully without being bothered.
Zod is the strict Bouncer at the end. Once you hand him the clipboard (submit), he checks your data against his strict rules ("Must be 18+", "Must have a valid email"). If you fail, he hands it back with specific red markers (errors). If you pass, you go in.
Installation
Strictly grab the latest packages:
npx expo install react-hook-form zod @hookform/resolversHow it works in practice
In Expo, standard HTML inputs (<input>) don't exist; we use <TextInput>. Because RHF needs to connect to React Native components, we use a wrapper called Controller provided by RHF.
import React from 'react';
import { View, Text, TextInput, Pressable, StyleSheet } from 'react-native';
import { useForm, Controller } from 'react-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
// 1. Define the validation rules (The Bouncer's Rules)
const schema = z.object({
email: z.string().email("Please enter a valid email"),
password: z.string().min(6, "Password must be at least 6 characters"),
});
export default function LoginForm() {
// 2. Initialize the form
const { control, handleSubmit, formState: { errors } } = useForm({
resolver: zodResolver(schema), // Connect Zod to RHF
defaultValues: { email: '', password: '' }
});
// 3. The function that runs ONLY if validation passes
const onSubmit = (data) => {
console.log("Valid data submitted to server:", data);
};
return (
<View style={styles.container}>
<Text style={styles.header}>Login</Text>
{/* Email Input */}
<Controller
control={control}
name="email"
render={({ field: { onChange, onBlur, value } }) => (
<TextInput
style={[styles.input, errors.email && styles.errorInput]}
placeholder="Email"
onBlur={onBlur}
onChangeText={onChange}
value={value}
autoCapitalize="none"
/>
)}
/>
{/* Show Error if exists */}
{errors.email && <Text style={styles.errorText}>{errors.email.message}</Text>}
{/* Password Input */}
<Controller
control={control}
name="password"
render={({ field: { onChange, onBlur, value } }) => (
<TextInput
style={[styles.input, errors.password && styles.errorInput]}
placeholder="Password"
onBlur={onBlur}
onChangeText={onChange}
value={value}
secureTextEntry
/>
)}
/>
{errors.password && <Text style={styles.errorText}>{errors.password.message}</Text>}
<Pressable style={styles.button} onPress={handleSubmit(onSubmit)}>
<Text style={{ color: 'white', textAlign: 'center' }}>Submit</Text>
</Pressable>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 20, justifyContent: 'center' },
header: { fontSize: 24, fontWeight: 'bold', marginBottom: 20 },
input: { borderWidth: 1, borderColor: '#ccc', padding: 15, borderRadius: 8, marginBottom: 5 },
errorInput: { borderColor: 'red' },
errorText: { color: 'red', marginBottom: 15, fontSize: 12 },
button: { backgroundColor: 'black', padding: 15, borderRadius: 8, marginTop: 10 }
});4. Introduction to Global State: Zustand
The Problem
If the Context API solves prop drilling, why do we need anything else? Performance and boilerplate. If you put your user data, cart data, and settings data into one giant Context, anytime anything updates, every single component using that Context re-renders. Redux Toolkit (RTK) solves this, but historically required a lot of boilerplate code (actions, reducers, slices, stores).
Definition: Zustand
Zustand (German for "state") is a small, fast, and scalable bearbones state-management solution using simplified flux principles. It allows you to create a global store using a custom hook, with zero boilerplate, and components can subscribe only to the specific pieces of data they need.
Real-Life Scenario: The Corporate Database
Imagine a massive company database containing everyone's salary, the cafeteria menu, and the CEO's schedule.
With Context API, every time the cafeteria runs out of soup, an alarm rings in the entire building and everyone stops working (re-renders).
With Zustand, employees (components) act differently. The HR component only subscribes to the "salary" data. The janitor component only subscribes to the "cafeteria" data. If the soup runs out, only the janitor is notified. Everyone else continues working efficiently.
Installation
npx expo install zustandHow it works in practice
In modern Expo/React Native apps, Zustand is often preferred for its incredible simplicity. Let's create a global store to hold a user's session.
// 1. Create the store (usually in a separate file like `useAuthStore.js`)
import { create } from 'zustand';
// Under the hood: Zustand creates an external state container outside of React.
// React components subscribe to it using a selector function.
export const useAuthStore = create((set) => ({
user: null,
isAuthenticated: false,
// Actions to mutate the state
login: (userData) => set({ user: userData, isAuthenticated: true }),
logout: () => set({ user: null, isAuthenticated: false }),
}));Now, anywhere in your app, you can use this hook. The beauty is in the selectors.
import React from 'react';
import { View, Text, Pressable } from 'react-native';
import { useAuthStore } from './useAuthStore'; // Import your store
export default function ProfileScreen() {
// We ONLY subscribe to 'user' and 'logout'.
// If another variable in the store changes, this component ignores it!
const user = useAuthStore((state) => state.user);
const logout = useAuthStore((state) => state.logout);
if (!user) {
return <Text>Please log in.</Text>;
}
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text style={{ fontSize: 20 }}>Welcome, {user.name}!</Text>
<Pressable
onPress={logout}
style={{ marginTop: 20, backgroundColor: 'red', padding: 10, borderRadius: 5 }}
>
<Text style={{ color: 'white' }}>Log Out</Text>
</Pressable>
</View>
);
}Industry tip: While Redux Toolkit (RTK) is still heavily used in legacy enterprise applications, Zustand has rapidly become the standard for new React Native/Expo projects because mobile apps benefit greatly from its lightweight footprint and ease of use.
📚 References and Further Reading
Do not just take our word for it. Dive deeper into the official documentation to see advanced patterns and API details:
Challenge
You are tasked with building a small user settings module for a mobile application. This module will manage a user's profile information (name, email) and a theme preference (light/dark).
Your goal is to implement this using modern state management libraries to ensure the application is performant and scalable.
Requirements:
Global State (Zustand):
- Create a global
Zustandstore to manage the application's state. - The store must contain the following state properties:
name(string),email(string), andtheme(either 'light' or 'dark'). - The store must expose actions to update each of these properties.
- Create a global
Profile Form (React Hook Form & Zod):
- Create a
ProfileFormcomponent. - Use
React Hook Formto manage the form state. - Define a validation schema using
Zod:namemust be a string with a minimum of 2 characters.emailmust be a valid email address string.
- Integrate the Zod schema with React Hook Form for validation.
- The form should have input fields for
nameandemailand a submit button. Use the<Controller>component to wrap the inputs. - Upon successful form submission, update the
nameandemailin the globalZustandstore.
- Create a
Header Component:
- Create a
Headercomponent that displays the user's name. - This component should subscribe only to the
nameproperty from theZustandstore to prevent unnecessary re-renders when other state properties (likeemailortheme) change.
- Create a
Theme Preference Component:
- Create a
ThemeTogglecomponent. - This component should display a button that, when pressed, toggles the
themevalue in theZustandstore between 'light' and 'dark'. - The button text should reflect the action (e.g., "Switch to Dark Mode").
- Create a
Side Effect (useEffect):
- In the main
Appcomponent, implement a side effect usinguseEffect. - This effect should listen for changes to the
themeproperty in theZustandstore. - Whenever the
themechanges, the effect should call the providedmockApiSave({ theme })function to simulate saving the preference to a server.
- In the main
Expected result
Your solution should correctly implement a complete state management system using Zustand, React Hook Form, and Zod.
1. Zustand Store (useUserStore)
The store should be created using create from zustand. It will initialize with default values for name, email, and theme, and include setter functions for each.
const useUserStore = create((set) => ({
name: 'Guest',
email: '',
theme: 'light',
setName: (name) => set({ name }),
setEmail: (email) => set({ email }),
setTheme: (theme) => set({ theme }),
}));2. Zod Schema (profileSchema)
The schema should define the validation rules for the form fields.
const profileSchema = z.object({
name: z.string().min(2, { message: 'Name must be at least 2 characters' }),
email: z.string().email({ message: 'Invalid email address' }),
});3. Header Component
The component should use the useUserStore hook with a selector function state => state.name to ensure it only re-renders when the name changes.
const name = useUserStore(state => state.name);
return (
<View style={styles.header}>
<Text style={styles.headerText}>Welcome, {name}</Text>
</View>
);4. ProfileForm Component
This component correctly sets up useForm with the zodResolver and the profileSchema. The onSubmit function should call the setName and setEmail actions from the Zustand store. The <Controller> components should be correctly configured for both name and email inputs.
const { setName, setEmail } = useUserStore();
const { control, handleSubmit, formState: { errors } } = useForm({
resolver: zodResolver(profileSchema),
defaultValues: { name: '', email: '' }
});
const onSubmit = (data) => {
setName(data.name);
setEmail(data.email);
};5. ThemeToggle Component
This component should get the current theme and the setTheme action from the store. The onPress handler for the button should call setTheme with the opposite value ('dark' or 'light').
const { theme, setTheme } = useUserStore();
const toggleTheme = () => {
setTheme(theme === 'light' ? 'dark' : 'light');
};6. App Component
The main component should contain the useEffect hook. It should select the theme from the store and include it in the dependency array. When the theme changes, the effect's callback function calls mockApiSave.
const theme = useUserStore(state => state.theme);
useEffect(() => {
// This check prevents it from running on initial mount
if (theme) {
mockApiSave({ theme });
}
}, [theme]); // Correct dependency array