External stores
Overview
Context + reducer works well, but every consumer re-renders whenever the context value changes. For larger apps — lots of shared state, frequent updates, many components reading small slices — teams usually reach for an external store: state that lives outside the React tree, with components subscribing to just the pieces they need.
This lesson uses Zustand, a small and popular store library, and then shows the React primitive underneath every store: useSyncExternalStore.
Zustand basics
npm install zustand// stores/cartStore.js
import { create } from 'zustand';
export const useCartStore = create((set, get) => ({
items: [],
addItem: (course) =>
set((state) => {
const existing = state.items.find((i) => i.id === course.id);
return {
items: existing
? state.items.map((i) => (i.id === course.id ? { ...i, qty: i.qty + 1 } : i))
: [...state.items, { ...course, qty: 1 }],
};
}),
removeItem: (id) => set((state) => ({ items: state.items.filter((i) => i.id !== id) })),
clear: () => set({ items: [] }),
total: () => get().items.reduce((sum, i) => sum + i.price * i.qty, 0),
}));createtakes a function receivingset(to update state) andget(to read the current state) and returns your initial state and actions.setmerges the object you return into the state (one level deep), so you only return what changed. Updates must still be immutable.createreturns a hook,useCartStore.
No provider is needed — the store is a module-level singleton.
Reading with selectors
Components call the hook with a selector that picks what they need:
function CartBadge() {
const count = useCartStore((s) => s.items.length);
return <span className="badge">🛒 {count}</span>;
}
function AddToCartButton({ course }) {
const addItem = useCartStore((s) => s.addItem);
return <button onClick={() => addItem(course)}>Add to cart</button>;
}
function CheckoutTotal() {
const total = useCartStore((s) => s.total());
return <p>Total: ${total.toFixed(2)}</p>;
}Zustand re-renders a component only when its selected value changes (compared with Object.is):
CartBadgere-renders when the number of items changes — not when a quantity changes.AddToCartButtonselects a function that never changes, so it never re-renders because of the cart.
That’s the key advantage over a single context.
Selecting several values
A selector that returns a new object or array would be “different” every time. Wrap it with useShallow, which compares the contents:
import { useShallow } from 'zustand/react/shallow';
const { items, clear } = useCartStore(
useShallow((s) => ({ items: s.items, clear: s.clear }))
);Alternatively, call the hook once per value — simple and just as efficient.
Using the store outside components
Because the store lives outside React, you can read and update it from anywhere — event listeners, API helpers, tests:
useCartStore.getState().addItem(course);
const items = useCartStore.getState().items;
const unsubscribe = useCartStore.subscribe((state) => console.log('cart changed', state));Middleware
Zustand ships useful middleware:
import { create } from 'zustand';
import { persist, devtools } from 'zustand/middleware';
export const usePrefsStore = create(
devtools(
persist(
(set) => ({
theme: 'light',
fontSize: 16,
setTheme: (theme) => set({ theme }),
}),
{ name: 'prefs' } // localStorage key
)
)
);persistsaves the state tolocalStorage(or another storage) and restores it on load.devtoolsconnects to the Redux DevTools browser extension, so you can see every update.immer(zustand/middleware/immer) lets you write mutating-style updates.
useSyncExternalStore
Under the hood, store libraries connect to React with useSyncExternalStore, a built-in hook for reading any external, mutable data source safely during concurrent rendering. You can use it directly for browser APIs:
import { useSyncExternalStore } from 'react';
function subscribe(callback) {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
window.removeEventListener('online', callback);
window.removeEventListener('offline', callback);
};
}
export function useOnlineStatus() {
return useSyncExternalStore(
subscribe, // how to subscribe to changes
() => navigator.onLine, // how to read the current value (client)
() => true // value to use during server rendering
);
}subscribe(callback)starts listening and returns an unsubscribe function. Define it outside the component so it’s the same function every render.getSnapshot()returns the current value. It must return the same value (or the same object) if nothing changed — returning a new object every time causes an infinite loop.- The optional third argument is used for server rendering and hydration.
Compared with useState + useEffect, it avoids “tearing”, where different parts of the UI briefly show different values during a concurrent render.
Choosing a state tool
| State | Tool |
|---|---|
| Local to one component | useState / useReducer |
| Shared by a few nearby components | lift state up |
| Rarely changing, app-wide (theme, user, locale) | context |
| App-wide UI state, moderate size | context + reducer, or a small store |
| Large or frequently updated client state | Zustand, Redux Toolkit, Jotai |
| Data from a server | TanStack Query, your router’s loaders |
| State in the URL (filters, tabs, page) | the router’s search params |
Redux Toolkit remains common in large, established codebases and is worth recognising: it has the same ideas — a store, actions, reducers, selectors — with more structure and tooling. Jotai takes an “atoms” approach, where state is split into many small independent pieces.
Most “global state” is server data. Before adding a store, move server data into a fetching library. What’s left over is usually small enough for context.
A Zustand course progress store
Create a Zustand store useProgressStore holding completed (an array of lesson ids) and actions complete(id) (adds the id if not already there) and reset(). Don’t store counts — compute them in components. Persist it to localStorage under the key progress. Write LessonCheck({ id }) that shows ✓ when complete and a button to mark it done, selecting only what it needs, and ProgressBar({ total }) showing “N of total complete”.
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
export const useProgressStore = create(
// your code here
);import { create } from 'zustand';
import { persist } from 'zustand/middleware';
export const useProgressStore = create(
persist(
(set) => ({
completed: [],
complete: (id) =>
set((state) =>
state.completed.includes(id) ? state : { completed: [...state.completed, id] }
),
reset: () => set({ completed: [] }),
}),
{ name: 'progress' }
)
);
export function LessonCheck({ id }) {
const isDone = useProgressStore((s) => s.completed.includes(id));
const complete = useProgressStore((s) => s.complete);
return isDone ? (
<span aria-label="Completed">✓</span>
) : (
<button onClick={() => complete(id)}>Mark done</button>
);
}
export function ProgressBar({ total }) {
const count = useProgressStore((s) => s.completed.length);
return (
<p>
<progress value={count} max={total} /> {count} of {total} complete
</p>
);
}Summary
- An external store holds state outside React; components subscribe to it and re-render when the part they use changes.
- Zustand creates a store with
create((set, get) => ({ …state, …actions }))and gives you a hook. - Select only what you need —
useStore(s => s.items.length)— so unrelated changes don’t re-render the component. - Use
useShallowwhen a selector returns a new object or array. useSyncExternalStore(subscribe, getSnapshot)is React’s built-in way to read any external data source safely.