Writing

Zustand in Production: Lessons from a Year of Scaling State in a Web3 Dashboard

Reading time: 6 minutes

In Part 1 I described how I put every chain behind one adapter interface so the UI of an institutional tokenization dashboard could stop caring which chain it was on. This part is about the other half of that work: state.

Over about a year, the state layer of that dashboard went through seven distinct shapes. None of them were planned up front. Each one was a response to a real problem: a bug report, a slow page, a confusing flicker. Looking back at the commit history, the sequence tells a more useful story than any “Zustand best practices” list, so here it is, in order, including the fix I had to revert.

Where it started: fetch it where you need it

The first version did what most dashboards do early on: components fetched wallet data when they needed it. The wallet list fetched wallets. The header fetched the selected wallet. The token picker fetched balances. Then the selected token got passed down through three or four layers of props to the components that used it.

It worked until it didn’t. The same wallet data was fetched several times per page load, components showed loading states at different moments, and every new screen meant threading the same props through more components. Two of my early commits say it plainly: eliminate duplicate wallet fetching and centralize token selection in store, remove prop drilling.

Step 1: one central store

The first fix was the obvious one: move wallet state into a single Zustand store, with one place that fetches, and give components a hook instead of props.

type WalletState = {
  wallets: Wallet[];
  selectedId?: string;
  status: "idle" | "loading" | "ready" | "error";
  load: () => Promise<void>;
  select: (id: string) => void;
};

export const useWalletStore = create<WalletState>()((set, get) => ({
  wallets: [],
  status: "idle",
  load: async () => {
    if (get().status === "loading") return; // one fetch, however many callers
    set({ status: "loading" });
    const wallets = await api.wallets();
    set({ wallets, status: "ready" });
  },
  select: (id) => set({ selectedId: id }),
}));

export const useWallet = () =>
  useWalletStore((s) => s.wallets.find((w) => w.id === s.selectedId));

Alongside it went small helpers for getting the signer for the selected wallet, so signing code stopped reaching into components for it. Duplicate fetches disappeared, and so did most of the prop drilling.

Step 2: split by domain

One store solved duplication, but it grew fast. Wallets, tokens and pending transactions all lived together, and a change to any of them could re-render components that only cared about one.

So I split it by domain: a wallet store, a token store and a transaction store, each in its own folder with its own types and actions.

stores/
  wallet/       types.ts · store.ts · selectors.ts
  token/        types.ts · store.ts · selectors.ts
  transaction/  types.ts · store.ts · selectors.ts

Two things improved immediately. Ownership became clear: when something is wrong with token balances, there is exactly one folder to look in. And re-renders got smaller: a component subscribed to the transaction store no longer re-renders because a token balance changed.

Step 3: caching, and the persistence bug

Next I added a caching layer so the dashboard did not refetch everything on every visit, using Zustand’s persist middleware. This is where I made the mistake worth writing about.

After shipping it, the token cache simply was not being saved. Wallets persisted, settings persisted, tokens did not. My first fix made the symptom go away, and I reverted it a day later because it was persisting far more than it should, including transient loading state.

The real lesson was about how persist and partialize work together:

export const useTokenStore = create<TokenState>()(
  persist(
    (set) => ({
      tokens: {},          // plain object, not a Map: JSON can't serialise a Map
      status: "idle",
      lastSyncedAt: undefined,
      // ...actions
    }),
    {
      name: "tokens",
      version: 2,
      // Persist data, never transient UI state.
      partialize: (s) => ({ tokens: s.tokens, lastSyncedAt: s.lastSyncedAt }),
      migrate: (persisted, version) => (version < 2 ? { tokens: {} } : persisted) as TokenState,
    },
  ),
);

The traps I now check for every time:

  • partialize is an allowlist. Anything it does not return is not saved. Forgetting one field looks exactly like “persist is broken”.
  • Persist only serialisable data. A Map, a class instance or a bigint does not survive JSON the way you expect. Store plain objects and strings, and convert at the edges.
  • Never persist status. Persisting status: "loading" means the next visit starts stuck in a loading state.
  • Version the shape. When the persisted shape changes, bump version and write a migrate, or old caches will quietly break new code.

Step 4: the performance problems

With more data in the stores, performance problems showed up in two forms: an infinite render loop on one screen, and a poor Largest Contentful Paint (LCP) score on the dashboard’s main page.

The render loop

The loop came from a selector that looked harmless:

// Buggy: returns a new object on every call
const { wallets, selectedId } = useWalletStore((s) => ({
  wallets: s.wallets,
  selectedId: s.selectedId,
}));

Every call creates a new object, so React sees a “changed” value on every render. Combine that with an effect that depends on it and writes back to the store, and you have a loop. The fix is to compare the picked fields shallowly:

import { useShallow } from "zustand/react/shallow";

const { wallets, selectedId } = useWalletStore(
  useShallow((s) => ({ wallets: s.wallets, selectedId: s.selectedId })),
);

The broader rule I adopted: select the smallest value a component needs, and never return a fresh object or array from a selector without useShallow.

Instant selection

Selecting a wallet used to feel slow because the UI waited for that wallet’s data before reflecting the click. The fix was to update state first, then fetch:

select: (id) => {
  set({ selectedId: id });        // the UI responds immediately
  void get().loadDetails(id);     // details arrive when they arrive
},

No flicker on refresh

When the cache was invalidated, the store cleared its data and showed a spinner, then filled back in. On a dashboard that refreshes often, that flicker made the product feel unstable. Now invalidation keeps the existing data and marks it stale while the refresh runs, and swaps in fresh data when it lands. The user keeps seeing numbers the whole time.

Together, these changes fixed the LCP problem on the main page: the largest element renders from cached data straight away instead of waiting behind a loading state.

Step 5: the URL and the store

Institutional users share links: “can you review this wallet’s pending transactions?”. So the selected wallet had to live in the URL as well as in the store, and a refresh or a shared link had to restore the right view.

Two sources of truth need a rule for who wins. Mine is:

  • On load, the URL wins. A link someone shared expresses intent; it should override whatever was last selected on this device.
  • After that, the store wins. User actions update the store, and the store writes back to the URL, replacing the history entry rather than pushing a new one.
export function useWalletUrlSync() {
  const params = useSearchParams();
  const router = useRouter();
  const pathname = usePathname();
  const selectedId = useWalletStore((s) => s.selectedId);
  const select = useWalletStore((s) => s.select);

  // 1. On load: URL → store
  useEffect(() => {
    const fromUrl = params.get("wallet");
    if (fromUrl && fromUrl !== selectedId) select(fromUrl);
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  // 2. Afterwards: store → URL
  useEffect(() => {
    if (!selectedId || params.get("wallet") === selectedId) return;
    const next = new URLSearchParams(params);
    next.set("wallet", selectedId);
    router.replace(`${pathname}?${next}`, { scroll: false });
  }, [selectedId]); // eslint-disable-line react-hooks/exhaustive-deps
}

If the wallet in the URL does not exist for this user, the store falls back to the default and the URL is corrected, so a stale link never leaves the page in a broken state.

Step 6: localStorage to IndexedDB

By now the persisted data had outgrown localStorage, for three reasons:

  • Size. localStorage gives you roughly 5 MB per origin. Decoded transactions and token metadata across several chains get there quickly.
  • It blocks. Every read and write is synchronous and runs on the main thread, so large writes show up as jank.
  • Shape. Multi-chain data is structured; IndexedDB stores structured values and handles larger datasets comfortably.

Zustand’s persist accepts any storage that implements getItem, setItem and removeItem, including async ones. With idb-keyval, the adapter is a few lines:

import { get, set, del } from "idb-keyval";
import { createJSONStorage, type StateStorage } from "zustand/middleware";

const idbStorage: StateStorage = {
  getItem: async (name) => (await get<string>(name)) ?? null,
  setItem: (name, value) => set(name, value),
  removeItem: (name) => del(name),
};

export const idbJSON = createJSONStorage(() => idbStorage);
// persist(..., { name: "tokens", storage: idbJSON, partialize, version })

The cost of going async is hydration: on first render, the store has not loaded from IndexedDB yet. I handle that once, in the store layer, using the store’s hydration status (useTokenStore.persist.hasHydrated() and onFinishHydration), so components render a skeleton until real data is in, instead of briefly showing empty state. Existing users were migrated by reading their old localStorage value once and writing it into IndexedDB.

Step 7: network-first state

The last step connects back to Part 1. Once the dashboard supported several chains, a single “wallet store” was the wrong shape: switching networks at the wrong moment could briefly show one chain’s data under another chain’s header.

So state became keyed by network: each chain gets its own store and its own persisted record, and clearing one network’s cache never touches the others. I covered the design and the reasoning in Part 1, because it only makes sense next to the adapter architecture.

What a year of this taught me

  • Let the problems drive the structure. Every one of these steps was a response to something real. Designing all seven up front would have produced the wrong architecture with more confidence.
  • Persistence is a contract. Decide exactly what is saved (partialize), keep it serialisable, version it, and never persist transient state.
  • Most performance bugs are subscription bugs. Select less, compare shallowly and never write to the store from an effect that depends on what you just wrote.
  • Make the UI respond before the network does. Optimistic updates and stale-while-refresh do more for perceived speed than most code optimisations.
  • Be explicit about sources of truth. When state lives in two places, like the URL and a store, write down which one wins and when.
  • Revert without ego. The persistence fix I reverted was the most educational commit in the whole history.