Global State Management

11 min read

Course: React Native

Topic: Global State Management

Hey there, future React Native wizards! 🧙‍♂️ Welcome to the guide on Global State Management.

So, you've been building components, passing data around with props, and things are going great. But then, your app starts to grow. You find yourself passing the same piece of data through five, ten, or even fifteen components, just to get it to a deeply nested component that actually needs it. This, my friends, is a headache known as "prop drilling," and we're here to learn how to cure it.

Global state management is the art of creating a centralized source of truth for your application's data, making it accessible to any component without the messy business of prop drilling. Let's dive in!


1. The Context API: Escaping Prop Drilling 📢

The Problem: What is Prop Drilling?

Imagine you're at the top of a five-story office building (your App component) and you need to deliver a very important piece of paper (a piece of state, like isDarkModeEnabled) to a colleague on the ground floor (a deeply nested Button component).

However, you can't just take the elevator. You have to hand the paper to someone on the fourth floor, who hands it to someone on the third, and so on, until it reaches its destination. Most of the people in this chain don't even need to look at the paper; they're just couriers.

This is prop drilling. It’s the process of passing props down through multiple layers of components that don’t need the props themselves. It makes your code verbose, hard to maintain, and frankly, a bit silly.

The Solution: React's Context API

The Context API is React's built-in solution to escape prop drilling. It allows you to create a "context," which acts like a global data store for a specific branch of your component tree. Any component within that branch can then access the data without it being passed down explicitly through every level.

Think of it as setting up a public announcement system for a section of your office building. You make an announcement at the top, and anyone with a receiver on any floor below can tune in and hear it directly.

How It Works: The Three Musketeers

  1. React.createContext(): This function creates the context object itself. You can give it a default value, which is useful for testing.
  2. <MyContext.Provider>: This is the component that makes the data available. You wrap it around a parent component, and any component nested under it can subscribe to the context's changes. It takes a value prop where you pass the data you want to share.
  3. useContext(MyContext): This is a hook that allows a functional component to subscribe to the context and get the latest value.

Example: A Simple Theme Switcher

Let's build a common use case: switching between a light and a dark theme.

Step 1: Create the Context
First, create a new file, let's call it ThemeContext.js.

javascript
// src/context/ThemeContext.js
import React, { createContext, useState } from 'react';

// 1. Create the context
export const ThemeContext = createContext();

// 2. Create the provider component
export const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState('light');

  const toggleTheme = () => {
    setTheme(currentTheme => (currentTheme === 'light' ? 'dark' : 'light'));
  };

  // The value that will be supplied to all consuming components
  const value = { theme, toggleTheme };

  return (
    <ThemeContext.Provider value={value}>
      {children}
    </ThemeContext.Provider>
  );
};

Step 2: Wrap Your App with the Provider
Now, go to your main App.js file and wrap your application with the ThemeProvider.

javascript
// App.js
import React from 'react';
import { ThemeProvider } from './src/context/ThemeContext';
import MainScreen from './src/screens/MainScreen';

export default function App() {
  return (
    <ThemeProvider>
      <MainScreen />
    </ThemeProvider>
  );
}

Step 3: Consume the Context in a Component
Any component inside ThemeProvider can now access the theme state.

javascript
// src/screens/MainScreen.js
import React, { useContext } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { ThemeContext } from '../context/ThemeContext';

const MainScreen = () => {
  // 3. Use the useContext hook to access the theme and toggle function
  const { theme, toggleTheme } = useContext(ThemeContext);

  const styles = getStyles(theme);

  return (
    <View style={styles.container}>
      <Text style={styles.text}>Current Theme: {theme}</Text>
      <Button title="Toggle Theme" onPress={toggleTheme} />
    </View>
  );
};

const getStyles = (theme) => StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: theme === 'light' ? '#FFF' : '#222',
  },
  text: {
    fontSize: 20,
    color: theme === 'light' ? '#000' : '#FFF',
  },
});

export default MainScreen;

And voilà! You've successfully managed a global theme state without drilling a single prop.

Industry Practice:
The Context API is fantastic for low-frequency updates like theming, user authentication status, or language preferences. However, be cautious about using it for state that updates very frequently (e.g., form inputs, animations), as every component consuming the context will re-render when the value changes, which can lead to performance issues.


2. Introduction to Zustand 🐻

The Problem: Context API's Performance Hiccups

As we just learned, the Context API is great, but it has a weakness. When the context value changes, all components that consume that context re-render. This is fine for a simple theme, but what if your global state has 20 different properties? If you only change one property, you still trigger a re-render in every component that uses any of the 20 properties. That's like recalling an entire product line just to fix a typo on one box.

The Solution: Zustand

Enter Zustand! Zustand is a small, fast, and scalable state management library. Its name is German for "state" – a fun little fact!

Zustand's magic lies in its hook-based approach. Components can subscribe to specific pieces of the state, and they will only re-render when that specific piece changes. This selective re-rendering makes it incredibly performant. Plus, there's minimal boilerplate—no providers, no reducers, no dispatchers in sight!

Installation
Getting started is a breeze. Just install the library:

bash
npm install zustand
# or
yarn add zustand

How It Works: Create a Store

With Zustand, you define all your state, and the functions that modify it (we call these "actions"), inside a create function. This returns a custom hook that you can use in any component to access the state.

Example: Shopping Cart Store

Let's create a store to manage a shopping cart.

Step 1: Create the Store
Create a new file src/stores/cartStore.js.

javascript
// src/stores/cartStore.js
import { create } from 'zustand';

export const useCartStore = create((set) => ({
  // State
  items: [],
  
  // Actions
  addItem: (item) => 
    set((state) => ({ items: [...state.items, item] })),
  
  removeItem: (itemId) => 
    set((state) => ({ items: state.items.filter(item => item.id !== itemId) })),
  
  clearCart: () => 
    set({ items: [] }),
}));

Step 2: Use the Store in Your Components

Now, any component can use this store. Notice how there's no <Provider> wrapping our app.

javascript
// src/components/ProductScreen.js
import React from 'react';
import { View, Text, Button } from 'react-native';
import { useCartStore } from '../stores/cartStore';

const ProductScreen = () => {
  // We only need the addItem action here
  const addItem = useCartStore((state) => state.addItem);

  const product = { id: 1, name: 'React Native T-Shirt', price: 25 };

  return (
    <View>
      <Text>{product.name} - ${product.price}</Text>
      <Button title="Add to Cart" onPress={() => addItem(product)} />
    </View>
  );
};

// src/components/CartDisplay.js
import React from 'react';
import { View, Text } from 'react-native';
import { useCartStore } from '../stores/cartStore';

const CartDisplay = () => {
  // This component only needs the number of items. It won't re-render
  // if other parts of the store change.
  const itemCount = useCartStore((state) => state.items.length);

  return (
    <View>
      <Text>Items in cart: {itemCount}</Text>
    </View>
  );
};

See how clean that is? ProductScreen only knows about the addItem function, and CartDisplay only knows about the number of items. If another value were added to the store, these components wouldn't re-render unnecessarily. That's the power of selective subscription!


3. Managing User Authentication State 🔐

The Problem: Who is Logged In?

One of the most common pieces of global state is user authentication. Your app needs to know, from almost every screen, whether a user is logged in. Based on this, you might show a login screen, a main dashboard, or a user profile page. Passing isAuthenticated and user objects as props everywhere would be a prop drilling catastrophe.

The Solution: An authStore

This is a perfect job for a global state manager like Zustand. We can create a dedicated authStore to hold the user's session information and provide actions for logging in and out.

Example: Building an Authentication Flow

Let's create a store to manage our user's authentication status.

Step 1: Create the authStore

javascript
// src/stores/authStore.js
import { create } from 'zustand';

export const useAuthStore = create((set) => ({
  // State
  isAuthenticated: false,
  user: null,
  token: null,
  
  // Actions
  login: (userData, token) => 
    set({
      isAuthenticated: true,
      user: userData,
      token: token,
    }),
  
  logout: () => 
    set({
      isAuthenticated: false,
      user: null,
      token: null,
    }),
}));

Step 2: Control Navigation Based on Auth State

In your app's entry point or root navigator, you can listen to the isAuthenticated state and show the correct screens.

javascript
// App.js or your main navigation file
import React from 'react';
import { useAuthStore } from './src/stores/authStore';
import AuthNavigator from './src/navigation/AuthNavigator'; // Contains Login, Signup screens
import AppNavigator from './src/navigation/AppNavigator';   // Contains main app screens

const App = () => {
  const isAuthenticated = useAuthStore((state) => state.isAuthenticated);

  return isAuthenticated ? <AppNavigator /> : <AuthNavigator />;
};

export default App;

Step 3: Call Actions from Screens
Your LoginScreen can call the login action, and a ProfileScreen can call logout.

javascript
// src/screens/LoginScreen.js
import React from 'react';
import { Button } from 'react-native';
import { useAuthStore } from '../stores/authStore';

const LoginScreen = () => {
  const login = useAuthStore((state) => state.login);

  const handleLogin = () => {
    // In a real app, you would make an API call here
    const fakeUserData = { id: '123', name: 'John Doe' };
    const fakeToken = 'supersecrettoken';
    login(fakeUserData, fakeToken);
  };

  return <Button title="Log In" onPress={handleLogin} />;
};

// src/screens/ProfileScreen.js
import React from 'react';
import { Button, Text, View } from 'react-native';
import { useAuthStore } from '../stores/authStore';

const ProfileScreen = () => {
  const { user, logout } = useAuthStore((state) => ({
    user: state.user,
    logout: state.logout,
  }));

  return (
    <View>
      <Text>Welcome, {user?.name}!</Text>
      <Button title="Log Out" onPress={logout} />
    </View>
  );
};

This pattern is clean, scalable, and keeps your authentication logic completely decoupled from your UI components.


4. Persisting Global State Across App Restarts 💾

The Problem: Your State Has Amnesia

So, your user logs in, and everything is great. They close the app to check a message and then re-open it a minute later... only to be greeted by the login screen again. What happened?

By default, all JavaScript state (including Zustand's) lives in memory. When the app closes, that memory is wiped clean. For a good user experience, we need our app to remember things, especially the user's login status.

The Solution: Zustand's persist Middleware

Zustand comes with powerful "middleware"—functions that can wrap your store and add extra capabilities. The persist middleware is designed for exactly this problem. It automatically saves your store's state to a storage medium (like AsyncStorage in React Native) and reloads it when the app starts.

Installation
You'll need a storage engine. The standard for React Native is @react-native-async-storage/async-storage.

bash
# For Expo projects
npx expo install @react-native-async-storage/async-storage

# For bare React Native projects
npm install @react-native-async-storage/async-storage
# Then for iOS
npx pod-install

Example: Making the authStore Persistent

Let's upgrade our authStore to remember the user.

javascript
// src/stores/authStore.js
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';

// 1. Wrap the create function with persist
export const useAuthStore = create(
  persist(
    (set) => ({
      isAuthenticated: false,
      user: null,
      token: null,
      
      login: (userData, token) => 
        set({
          isAuthenticated: true,
          user: userData,
          token: token,
        }),
      
      logout: () => 
        set({
          isAuthenticated: false,
          user: null,
          token: null,
        }),
    }),
    {
      // 2. Provide a unique name for the storage key
      name: 'auth-storage', 
      
      // 3. Use AsyncStorage as the storage medium
      storage: createJSONStorage(() => AsyncStorage), 
    }
  )
);

And that's it! With just a few lines of code, your authentication state is now persisted. When the user logs in, their data is saved to the device. When they re-open the app, Zustand's middleware automatically performs "hydration," which is the process of retrieving the saved state from storage and putting it back into the store before your app renders.

Industry Practice:
Be selective about what you persist. You don't need to save everything. The persist middleware allows you to whitelist or blacklist parts of your state. For example, you should persist the user's token and theme preference but avoid persisting temporary UI state like loading indicators or sensitive information that shouldn't be stored unencrypted on the device.


Congratulations! You've journeyed from the pains of prop drilling to building a robust, performant, and persistent global state management system. You're now equipped with the industry-standard tools and patterns to handle complex state in any React Native application. Happy coding! 🚀

📚 References for Extra Reading

Challenge

You are building a settings management system for a React Native application. Your task is to create a Zustand store to handle user preferences and session data, ensuring only non-sensitive information is persisted across app restarts.

Requirements:

  1. Import create from 'zustand', persist from 'zustand/middleware', and asyncStorage from the provided mock environment.
  2. Define and create a Zustand store named useSettingsStore.
  3. The store's initial state must contain:
    • theme: A string, defaulting to 'light'.
    • sessionToken: A string or null, defaulting to null.
  4. Implement the following actions within the store:
    • toggleTheme(): A function that switches the theme between 'light' and 'dark'. For example, if the current theme is 'light', it should become 'dark', and vice versa.
    • setToken(token): A function that accepts a string token and updates the sessionToken in the state.
    • clearToken(): A function that resets sessionToken to null.
  5. Wrap your store definition with the persist middleware.
    • The persistence configuration must use the key 'user-settings'.
    • Use the provided asyncStorage as the storage engine.
    • Crucially, configure the middleware to only persist the theme state. The sessionToken must not be saved to storage.

Expected result

Your solution should be a single constant, useSettingsStore, assigned the result of a call to create().

The create() function should be wrapped by the persist() middleware function.

The persist function's first argument is the store's creator function, and its second argument is a configuration object with the following properties:

  • name: The string 'user-settings'.
  • storage: An object that correctly references the asyncStorage mock.
  • partialize: A function (state) => ({ theme: state.theme }) which ensures only the theme slice of the state is persisted.

Inside the store creator function, you should define:

  • The initial state properties theme and sessionToken with their default values.
  • The toggleTheme action, which uses the set function to correctly flip the theme value based on its current value.
  • The setToken action, which accepts a token and updates the state.
  • The clearToken action, which resets the sessionToken to null.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.