# Scope stores with context

Use a context provider when a reusable component needs its own state, initialized from props, rather than an application-wide singleton. Each provider below owns independent counters; the tabbed example also retains a separate counter for each key.

Here, each provider retains its own instance created with [`createStore`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#createstore) and supplies it through context to [`useStore`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#usestore); see [Stores and React bindings](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/store-and-react-binding) for vanilla stores versus bound hooks.

Start from the project in the [React quick start](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start). It already includes Zustand, so these steps add no dependencies. Only swap the rendered component for these examples; see [Organize store actions](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/organize-store-actions) for entry-file wiring.

## 1. Create a store initialized from props

Add a factory rather than a singleton. Each call returns a new store with its own initial count and action. The returned instance has the library's [`StoreApi`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#storeapi) methods; `ReturnType` preserves the factory's inferred instance type without copying that interface.

```ts title="src/scoped-counter-store.ts"
import { createStore } from 'zustand'

export type CounterProps = { count: number }

export type CounterState = CounterProps & {
  increment: () => void
}

export function createCounterStore(initialProps?: Partial<CounterProps>) {
  return createStore<CounterState>()((set) => ({
    count: 0,
    ...initialProps,
    increment: () => set((state) => ({ count: state.count + 1 })),
  }))
}

export type CounterStore = ReturnType<typeof createCounterStore>
```

The factory follows the authors' dependency-injection pattern: defaults first, initial props second, actions last. The updater passed to `set` returns a new partial state; `set` shallowly merges it, preserving the action.

## 2. Give each provider an isolated store

Add this component module. The provider's lazy `useState` initializer retains the store across renders. The custom hook reads the context, rejects a missing provider, and passes the selector to `useStore`. Its generic return type follows the selector: selecting `count` returns a number, while selecting `increment` returns the action.

```tsx title="src/ScopedCounters.tsx"
import { createContext, useContext, useState } from 'react'
import type { PropsWithChildren } from 'react'
import { useStore } from 'zustand'
import { createCounterStore } from './scoped-counter-store'
import type {
  CounterProps,
  CounterState,
  CounterStore,
} from './scoped-counter-store'

const CounterContext = createContext<CounterStore | null>(null)

function CounterProvider({
  children,
  count,
}: PropsWithChildren<CounterProps>) {
  const [store] = useState(() => createCounterStore({ count }))
  return (
    <CounterContext.Provider value={store}>
      {children}
    </CounterContext.Provider>
  )
}

function useCounterContext<U>(selector: (state: CounterState) => U): U {
  const store = useContext(CounterContext)
  if (store === null) {
    throw new Error('useCounterContext requires CounterProvider')
  }
  return useStore(store, selector)
}

function Counter({ label }: { label: string }) {
  const count = useCounterContext((state) => state.count)
  const increment = useCounterContext((state) => state.increment)
  return (
    <section>
      <h2>{label}</h2>
      <p aria-live="polite">Count: {count}</p>
      <button type="button" onClick={increment}>+1</button>
    </section>
  )
}

export default function ScopedCounters() {
  return (
    <main style={{ minHeight: 400, padding: 24 }}>
      <h1>Isolated counters</h1>
      <CounterProvider count={2}>
        <Counter label="First counter" />
      </CounterProvider>
      <CounterProvider count={10}>
        <Counter label="Second counter" />
      </CounterProvider>
    </main>
  )
}
```

In `src/main.tsx`, change the quick start's `Counter` import to `ScopedCounters` from `./ScopedCounters.tsx` and render `<ScopedCounters />` in its place. Build and run the project:

```bash
npm run build
npm run dev
```

The page displays two counters starting at 2 and 10. Click the first **+1** button: only the first count increases. Consumers beneath the same provider share its store; consumers beneath separate providers do not.

![Look at the initial counts: the first counter starts at 2 and the second at 10, each with its own +1 button.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/e4fd546816ab694b8fc36517177f063c.png)

## 3. Select dynamically keyed stores through context

For tabs, place a map of stores in the provider instead of one store. Retrieve an existing instance by key, or create it on first use. Switching tabs changes the instance passed to `useStore`, while the map retains the inactive tabs' state.

Add the following module. It reuses the factory from step 1. Each workspace owns a separate map, so even matching tab keys in different workspaces remain isolated.

```tsx title="src/KeyedCounters.tsx"
import { createContext, useCallback, useContext, useState } from 'react'
import type { PropsWithChildren } from 'react'
import { useStore } from 'zustand'
import { createCounterStore } from './scoped-counter-store'
import type { CounterState, CounterStore } from './scoped-counter-store'

type CounterStores = Map<string, CounterStore>

function createCounterStoreFactory(stores: CounterStores) {
  return (key: string): CounterStore => {
    const existing = stores.get(key)
    if (existing) return existing
    const store = createCounterStore()
    stores.set(key, store)
    return store
  }
}

const CounterStoresContext = createContext<CounterStores | null>(null)

function CounterStoresProvider({ children }: PropsWithChildren) {
  const [stores] = useState(() => new Map<string, CounterStore>())
  return (
    <CounterStoresContext.Provider value={stores}>
      {children}
    </CounterStoresContext.Provider>
  )
}

function useKeyedCounter<U>(
  key: string,
  selector: (state: CounterState) => U,
): U {
  const stores = useContext(CounterStoresContext)
  const getOrCreateStore = useCallback(
    (storeKey: string) => {
      if (stores === null) {
        throw new Error('useKeyedCounter requires CounterStoresProvider')
      }
      return createCounterStoreFactory(stores)(storeKey)
    },
    [stores],
  )
  return useStore(getOrCreateStore(key), selector)
}

function Tabs({ label }: { label: string }) {
  const [currentTab, setCurrentTab] = useState(0)
  const key = `tab-${currentTab}`
  const count = useKeyedCounter(key, (state) => state.count)
  const increment = useKeyedCounter(key, (state) => state.increment)
  return (
    <section>
      <h2>{label}</h2>
      <div style={{ display: 'flex', gap: 8 }}>
        {[0, 1, 2].map((index) => (
          <button
            key={index}
            type="button"
            aria-pressed={currentTab === index}
            onClick={() => setCurrentTab(index)}
          >
            Tab {index + 1}
          </button>
        ))}
      </div>
      <p aria-live="polite">Tab {currentTab + 1}: {count}</p>
      <button type="button" onClick={increment}>+1</button>
    </section>
  )
}

export default function KeyedCounters() {
  return (
    <main style={{ minHeight: 400, padding: 24 }}>
      <h1>Keyed counters</h1>
      <CounterStoresProvider>
        <Tabs label="First workspace" />
      </CounterStoresProvider>
      <CounterStoresProvider>
        <Tabs label="Second workspace" />
      </CounterStoresProvider>
    </main>
  )
}
```

Change the component import in `src/main.tsx` to `KeyedCounters` from `./KeyedCounters.tsx` and render `<KeyedCounters />`, keeping the rest of the entry file. Run the same build and development commands.

Both workspaces initially show Tab 1 with count 0. Increment Tab 1 in the first workspace, switch to Tab 2, then return to Tab 1: its count remains. The second workspace's Tab 1 remains at 0.

![Each workspace displays three tab buttons, Tab 1 with count 0, and a +1 button.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/dd00f37c2439e44eb831efcf2b1e2a1b.png)

The authors also show dynamic global stores: the same get-or-create factory can use a module-level map when all consumers deliberately share keyed instances. The provider-local map here limits sharing to one subtree.

## Options that determine scope

These are application-level choices, not Zustand configuration options.

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `initialProps` in `createCounterStore` | `Partial<CounterProps>` | Count 0 when omitted | Supplies initial data for a new instance. |
| `count` on `CounterProvider` | `number` | Required | Initializes that provider's store. |
| `key` in `useKeyedCounter` | `string` | Required | Selects one retained instance within the provider's map. |
| `selector` in either custom hook | `(state: CounterState) => U` | Required | Selects the subscribed value returned to the component. |

`useStore(store)` also returns the entire state when you omit its selector. The custom hooks require selectors so each consumer explicitly chooses its subscription.

## Pitfalls

- Treat provider props as initialization, not synchronization. The lazy initializer does not apply later `count` prop changes to the existing store. To start a new independent lifetime, mount a new provider, for example by changing its React `key`.
- Keep the provider above every consumer. Both hooks throw when their context has no provider rather than creating a silently shared fallback store.
- Choose keys that identify the data, not a changing display position. The keyed factory retains every requested key for the lifetime of its map; this example does not evict stores.
- For selectors that compute objects or arrays, use the patterns in [Select computed state](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/select-computed-state). For a custom equality function, see [Customize equality checks](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/customize-equality-and-subscriptions).
- For server request isolation and matching server/client initial state, see [Server-render React stores](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/server-render-react-stores).

## Live demo and related guides

Explore the [live Zustand demo](https://zustand-demo.pmnd.rs/) for the counter's selector-and-action interaction. The examples above add provider-local instance ownership to that pattern.

- [Stores and React bindings](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/store-and-react-binding) explains vanilla stores versus bound hooks.
- [Type stores and selectors](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/type-stores-and-selectors) covers store types and selector inference.
- [Test stores and components](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/test-stores-and-components) covers testing state changes and React consumers.
