Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 71 ยท State and Data

Global State with Zustand and Redux Toolkit

Share state across React Native screens with Zustand or Redux Toolkit, use selectors to avoid extra re-renders, and persist stores. Includes live mini-store demos.

Context and useReducer carry you a long way, as you saw in State in React Native Apps. But a mobile app has some state that many screens need at once: the signed-in user, the shopping cart, the chosen theme, a list of downloads. A store is a small object that lives outside your components, holds that state, and tells interested components when it changes.

Two stores dominate React Native projects. Zustand is tiny and almost free of ceremony. Redux Toolkit (RTK) is larger, more structured, and comes with excellent debugging tools. This lesson shows both, explains the one idea that matters most for performance (selectors), and then how to keep the store alive across app launches.

What runs on this site. Zustand, Redux Toolkit and the persistence libraries are shown as read-only code, because they are installed with npm in a real project. The runnable examples are stand-ins: a mini store built on React's own useSyncExternalStore, and a mini persistence layer with an in-memory "disk". They show how the real libraries work inside, but they are not the libraries.

Why a store at all?

Mobile navigation keeps several screens alive at once (a tab bar keeps every tab mounted, a stack keeps the screens below the top). If a cart lives in one screen's useState, the other screens cannot see it. You could lift it to the root component and pass it down, or put it in context, but context re-renders every consumer whenever the value changes. A store lets each component subscribe to only the slice it cares about.

What belongs in a store

Cart Many screens read and change it.
Session Who is signed in, and their settings.
Preferences Theme, language, units.
Not server data Cached API results fit TanStack Query better.

Keep screen-only state, like a text field's value, in useState.

1 / 2

Zustand in a few lines

You create a store with create. The function you pass receives set (to update state) and get (to read it), and returns the initial state together with the actions.

JSX
import { create } from 'zustand';

export const useCartStore = create((set, get) => ({
  items: [],
  addItem: (item) => set((state) => ({ items: [...state.items, item] })),
  clear: () => set({ items: [] }),
  total: () => get().items.reduce((sum, i) => sum + i.price, 0),
}));

create returns a hook. There is no provider to wrap around the app. Any component can call it:

JSX
import { Text, Pressable } from 'react-native';
import { useCartStore } from './cartStore';

export function CartBadge() {
  const count = useCartStore((state) => state.items.length);
  return <Text>{count}</Text>;
}

export function AddButton({ product }) {
  const addItem = useCartStore((state) => state.addItem);
  return (
    <Pressable onPress={() => addItem(product)}>
      <Text>Add to cart</Text>
    </Pressable>
  );
}

set merges the object you give it into the current state, much like the old class setState. You never mutate state directly: you return new arrays and objects.

Selectors decide who re-renders

The function you pass to the hook, (state) => state.items.length, is a selector. Zustand runs it after every change and compares the result with the previous result using Object.is. The component re-renders only when the selected value is different.

That makes selector choice the main performance tool:

  • Select the smallest value you need. CartBadge above re-renders only when the item count changes, not when something else in the store changes.
  • Do not call the hook with no selector (const state = useCartStore()) in a busy screen: the component then re-renders on every change.
  • Selecting several values? Returning a fresh object or array, such as (s) => ({ a: s.a, b: s.b }), creates a new reference on every check. In Zustand 5 this can loop forever, so wrap it with useShallow, which compares the contents instead:
JSX
import { useShallow } from 'zustand/react/shallow';

const { items, clear } = useCartStore(
  useShallow((state) => ({ items: state.items, clear: state.clear })),
);

Actions are a nice case: functions defined once in the store never change identity, so selecting an action never causes a re-render.

Try this yourself. The stand-in store below uses useSyncExternalStore, the same React primitive that Zustand's hook is built on. Three components read the same store. Press the buttons and watch which render counters move.

A mini store and its selectors

Press "Increment count" a few times: CountBadge and Everything re-render, NameBadge does not. Press "Rename user" and the roles swap. That is the whole point of selectors.

Redux Toolkit

Redux Toolkit is the official, modern way to write Redux. You describe a piece of state as a slice: a name, initial state and reducers. RTK uses a library (Immer) that lets you write code that looks like mutation inside reducers while producing a new immutable state for you.

JSX
// store/cartSlice.js
import { createSlice } from '@reduxjs/toolkit';

const cartSlice = createSlice({
  name: 'cart',
  initialState: { items: [] },
  reducers: {
    itemAdded(state, action) {
      state.items.push(action.payload); // safe: Immer makes this immutable
    },
    cartCleared(state) {
      state.items = [];
    },
  },
});

export const { itemAdded, cartCleared } = cartSlice.actions;
export default cartSlice.reducer;
JSX
// store/index.js
import { configureStore } from '@reduxjs/toolkit';
import cart from './cartSlice';

export const store = configureStore({ reducer: { cart } });

Unlike Zustand, Redux needs a Provider near the root, and components use useSelector and useDispatch:

JSX
import { Provider, useSelector, useDispatch } from 'react-redux';

function CartBadge() {
  const count = useSelector((state) => state.cart.items.length);
  return <Text>{count}</Text>;
}

function AddButton({ product }) {
  const dispatch = useDispatch();
  return (
    <Pressable onPress={() => dispatch(itemAdded(product))}>
      <Text>Add to cart</Text>
    </Pressable>
  );
}

export default function App() {
  return (
    <Provider store={store}>
      <Navigation />
    </Provider>
  );
}

useSelector works just like a Zustand selector: it re-renders when the returned value changes by reference. The extra structure buys you a single stream of named actions, so the Redux DevTools can show every change and even replay them. On a large team that traceability is often worth the extra files. RTK also ships RTK Query for server data, which overlaps with TanStack Query.

Persisting a store between launches

Quit and reopen the app, and every store is empty again, because state lives in memory. To keep the cart or the theme, save the state to storage and load it at startup. Storage in React Native is asynchronous (see Storing Data: AsyncStorage, MMKV and SecureStore).

Zustand has a persist middleware for exactly this:

JSX
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';

export const usePrefs = create(
  persist(
    (set) => ({
      theme: 'light',
      search: '',
      setTheme: (theme) => set({ theme }),
    }),
    {
      name: 'prefs',                                   // storage key
      storage: createJSONStorage(() => AsyncStorage),  // where to save
      partialize: (state) => ({ theme: state.theme }), // save only this
      version: 2,                                      // schema version
      migrate: (saved, version) => (version < 2 ? { theme: saved.dark ? 'dark' : 'light' } : saved),
    },
  ),
);

Three options deserve attention. partialize stops temporary state (a search box, a loading flag) from being saved. version and migrate let a new app release read data written by an old one. And because storage is async, the store starts with its initial values and hydrates a moment later, so screens should wait (for example behind the splash screen) until usePrefs.persist.hasHydrated() is true. Redux has the same idea in the separate redux-persist package, which wraps your reducer and adds a PersistGate component that waits for hydration.

Here is the idea in miniature, with an in-memory object pretending to be the disk. "Restart app" builds a brand new store that must hydrate from that disk, just like a cold start. Try "Seed old v1 data" first, then restart, to watch a migration run.

Persistence, partialize and migration

Notice that the search text never reaches the disk, and that after a restart the store briefly reports hydrated: false. Real apps hide the screen (or keep the splash screen up) during that moment.

Choosing and structuring

  • One store or many? Zustand encourages several small stores (cart, prefs, session). Redux uses one store combined from slices. Both are fine; avoid one giant bag of unrelated state.
  • Derive, do not duplicate. Store the cart items and compute the total with a selector. Two copies of the same truth drift apart.
  • Keep server data out. Lists fetched from an API have loading, stale and error states that a store does not manage for you.
  • Never store secrets in a persisted store. AsyncStorage is not encrypted; tokens belong in secure storage.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a selector like (state) => state.items.length do in Zustand?

    The selector picks a slice of state. Zustand compares the result with the previous one using Object.is and re-renders the component only when it differs.
  2. 2. Why wrap a multi-value selector in useShallow in Zustand 5?

    A fresh object or array has a new reference on every check, so Object.is always says it changed. useShallow compares the contents instead.
  3. 3. What is the job of partialize in persistence middleware?

    partialize returns the subset of state to write to storage, so temporary values such as a search box or a loading flag are not saved.
  4. 4. Which statement about Redux Toolkit is true?

    createSlice uses Immer, so state.items.push(x) inside a reducer is safe. You still need a Provider at the root, and the DevTools are a main benefit.

Summary

  • A store holds state outside components so many screens can share it; keep screen-only state in useState and server data in a query library.
  • Zustand: create returns a hook, no provider, state changes with set; selectors decide which components re-render, and useShallow handles multi-value selections.
  • Redux Toolkit: createSlice, configureStore, Provider, useSelector and useDispatch; more structure and excellent devtools.
  • Persist with middleware (Zustand persist, or redux-persist): use partialize, version and migrate, and wait for hydration before showing screens.
  • Never persist secrets in plain storage.
  • On this site the libraries are read-only; the mini store and persistence layer are stand-ins.

Next, learn how to load data from a server with Networking with fetch.