Persisting Zustand state
You can persist the cart across app restarts while keeping authentication tokens out of AsyncStorage, so checkout can reuse its idempotency key.
Learning outcomes
- Explain how Zustand stores shared client state and how selectors limit component re-renders.
- Describe how the persist middleware saves cart data to AsyncStorage and how partialize controls persisted fields.
- Distinguish initial store state from restored state during asynchronous hydration.
- Explain why authentication tokens belong in secure storage and how an idempotency key identifies one checkout across app restarts.
The cart needs to survive two things that ordinary component state does not: navigation between screens and the customer closing the app. The Cart tab needs its item count, the configurator needs to add lines, and the cart screen needs to update quantities and submit an order. All three must see the same cart, even after an app restart.
The cart also owns an idempotency key. If the server creates an order but the response disappears, the customer must be able to retry with the same key. That means the cart needs shared state and persistent storage.
Shared client state
The cart is client state. The backend does not maintain a separate cart. It receives the selected items when the customer places an order.
You have three common ways to share state in React:
useStatekeeps state inside a component. Other screens cannot directly share that state, and unmounting the owning screen discards it.- React Context makes state available to multiple components. However, when its value changes, consumers of that context can re-render even when they only need an unchanged part of the value.
- TanStack Query manages server state. The cart has no server endpoint to fetch or update before checkout.
Zustand provides a small external store that fits this problem. You define state and actions together, then components subscribe to the values they need.
A store can be created without putting its state inside a screen:
import { create } from "zustand";
type CounterState = {
count: number;
increment(): void;
};
const useCounter = create<CounterState>()(set => ({
count: 0,
increment: () => set(s => ({ count: s.count + 1 })),
}));create returns a hook called useCounter. The store starts with count: 0 and exposes an action that updates it.
Two arguments matter:
setupdates the store. It accepts a partial state object or a function of the current state.getreads the current state without subscribing a component.
Actions live alongside the data. Every caller uses the same state transitions instead of implementing its own cart update logic.
Notice that increment returns a new state value. You should not modify the existing state directly. When an action updates an array or object, create a new one so React and Zustand can detect the change.
Cart data
A cart line needs to preserve the customer's choices as well as the quoted price. The choices must use the same structure as the menu pricing endpoint and the order lines.
The chosen field maps a group ID to an array of option IDs:
type Chosen = Record<string, number[]>;
const chosen: Chosen = {
crust: [3],
toppings: [8, 12],
};This structure keeps selections grouped by their menu group. It can represent more than one selected option in a group.
The cart line also carries:
itemIdandsizeto identify the configured menu item.qtyto record how many units the customer wants.unitPaiseto hold the quoted unit price.descriptionto preserve the description associated with the quote.
Money stays in integer paise. Do not convert it to a floating-point rupee value for calculations. Formatting belongs in the UI.
Selectors and subscriptions
A component should subscribe only to the part of the cart it displays. Zustand accepts a selector function as the argument to its hook.
For example, the cart screen can select its lines and total separately:
const lines = useCart(s => s.lines);
const total = useCart(s => s.total());The Cart tab needs a different value. Its badge counts the quantity of items, not the number of cart lines.
const count = useCart(s =>
s.lines.reduce((sum, line) => sum + line.qty, 0)
);If the cart contains two lines with quantities 2 and 3, the badge shows 5. Using lines.length would show 2 instead.
A selector returning a primitive value, such as a number, gives Zustand a straightforward value to compare. If the selected count stays unchanged, editing an unrelated field such as a description does not require the tab to re-render.
Object selectors
Be careful when a selector constructs a new object.
const cart = useCart(s => ({
lines: s.lines,
total: s.total(),
}));The selector creates a new object reference whenever it runs. Even when the underlying values have not meaningfully changed, the new reference can trigger unnecessary updates.
Prefer separate selectors when you need independent values. When you genuinely need several values together, useShallow from zustand/react/shallow can compare the selected object's properties shallowly.
Reading outside a component
Checkout code may need the latest cart state inside an event handler or another module. That code does not need a React subscription.
Use the store's getState() method:
const cart = useCart.getState();
const key = cart.idempotencyKey;
const lines = cart.lines;This reads the current store state and gives you access to its actions. It does not subscribe the calling code to future changes.
Persisting the cart
A Zustand store normally lives in memory. Closing the app removes that in-memory state. To restore it after a restart, you need storage that survives the process.
The persist middleware wraps the store and saves its state whenever it changes. It also restores the saved state when the app launches.
For the cart, use AsyncStorage with the storage name cart:
import AsyncStorage from "@react-native-async-storage/async-storage";
import { createJSONStorage, persist } from "zustand/middleware";
persist(storeFunction, {
name: "cart",
storage: createJSONStorage(() => AsyncStorage),
});createJSONStorage adapts AsyncStorage to the storage interface expected by the middleware. The name identifies the stored entry.
After an update, the middleware serializes the state as JSON. The stored value has a state field and a version field. JSON serialization does not preserve functions, so the action implementations are supplied by the store code on the next launch.
For the cart, the data that matters is:
restaurantId, ornullwhen there is no active cart.lines, containing the cart lines.idempotencyKey, ornullwhen there is no active checkout.
Selecting persisted fields
The partialize option lets you control which state fields are saved. This is useful when a store contains values that should remain in memory but should not be restored from storage.
For example, the cart's persisted data can be limited to its three data fields:
partialize: state => ({
restaurantId: state.restaurantId,
lines: state.lines,
idempotencyKey: state.idempotencyKey,
})This keeps the storage contract explicit. You do not need to persist action functions because the application recreates them from the store definition.
Choosing storage for sensitive data
AsyncStorage is appropriate for the cart because the cart is ordinary application state. It is not encrypted storage.
Authentication tokens require a different decision. An access token and a refresh token can grant access to a customer's account. Exposing either one can allow someone else to act as that customer.
The app uses expo-secure-store for sensitive authentication data. Secure storage uses the device's protected storage facilities rather than treating credentials as ordinary application preferences.
Keep the responsibilities separate:
| Data | Storage |
|---|---|
| Cart lines | AsyncStorage |
| Restaurant ID | AsyncStorage |
| Idempotency key | AsyncStorage |
| Access token | Secure storage |
| Refresh token | Secure storage |
Hydration
Restoring persisted state is asynchronous. The Zustand store exists before AsyncStorage finishes reading the saved cart.
This process is called Hydration. It replaces the initial in-memory state with the data loaded from storage.
Consider a customer who previously had three items in the cart. When the app launches, the sequence is:
- The Zustand store is created with its initial empty state.
- The persist middleware reads the saved entry from AsyncStorage.
- The saved restaurant, lines and idempotency key are restored.
- Components receive the restored state through their subscriptions.
The first render can therefore show an empty cart even though the customer has previously saved items.
The persist middleware exposes methods for checking this state:
useCart.persist.hasHydrated();
useCart.persist.onFinishHydration(state => {
console.log("Cart restored:", state.lines.length);
});hasHydrated() reports whether the saved state has finished loading. onFinishHydration() lets you register a callback for that event.
These methods matter when application logic makes decisions based on cart contents. An empty cart before hydration does not mean the customer has no saved items.
The idempotency key lifecycle
The idempotency key identifies one checkout. It is sent in the Idempotency-Key header to POST /v1/orders.
The backend uses this key to prevent a retry from creating another order. If the first request succeeds but its response gets lost, the app can retry with the same key and receive the existing order.
The cart must therefore own the key rather than generating one every time the customer presses Place order.
The key follows these rules:
- An empty cart has no idempotency key.
- The first accepted
addcreates a key. - Further additions and quantity changes retain the existing key.
replaceWithstarts a new cart and creates a new key.- Removing the last cart line deletes the key.
clear()resets the cart and deletes the key.- Persisting the cart also persists its key, so a restart does not create a different checkout identity.
The key can be generated with crypto.randomUUID(), with a fallback for environments where that API is unavailable.
The important distinction is between an edit to the current checkout and the beginning of a new checkout. Changing a quantity does not create a new checkout. Replacing the cart does.


Why persistence matters for checkout
Imagine the customer submits an order while travelling through an area with an unreliable connection.
The server receives the request and creates the order. However, the response never reaches the phone. The customer closes the app and returns later.
If the cart and its idempotency key survived the restart, the customer can retry using the same key. The backend recognises the request as a retry instead of creating another order.
Generating a new key for every button press would break this guarantee. Losing the key during hydration or restarting would have the same problem.
Cart checkout boundary
The next exercise, Persisted cart store, brings these pieces together in app/lib/cart.ts. Its actions define when the cart changes, while the persist middleware keeps the cart and its idempotency key across app restarts.
The Cart tab has a narrower responsibility. It selects the sum of cart-line quantities and displays that number as its badge. It does not need the full cart state.
Keep the storage and subscription boundaries clear. AsyncStorage preserves non-sensitive cart data, secure storage protects authentication tokens, and hydration determines when restored cart data is ready to use.
Check your understanding
The cart contains two lines. Their quantities are 2 and 3. The Cart tab uses a selector to calculate the badge count. The customer changes the description of the first line without changing either quantity. Which behaviour should you expect?
References
Everything above is explained on this page; these are where it comes from (Zustand 5, AsyncStorage 2).