# Type stores and selectors

Use TypeScript to describe state and actions, infer their types with middleware, and generate per-field hooks for bound and vanilla stores. Each example below renders a store-backed control so you can see its updates.

Start from the project in the [React quick start](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start). These examples use its React and TypeScript setup and its existing `zustand` installation. Add the files below, then wire the panels into `App` as shown at the end; keep the starter's entry file, `StrictMode` wrapper, and stylesheet imports.

## Creating a store with state and actions

1. Describe your application's data and actions in one interface.
2. Pass that interface to [`create`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#create) using `create<BearState>()(...)`.
3. Select each value and action in your component.

The returned hook has type [`UseBoundStore`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#useboundstore)`<`[`StoreApi`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#storeapi)`<BearState>>`: it subscribes React components and also exposes methods such as `getState()` and `setState()`.

```tsx title="src/TypedBears.tsx"
import { create } from 'zustand'

interface BearState {
  bears: number
  food: string
  feed: (food: string) => void
  increase: (by: number) => void
  reset: () => void
}

const initialState = { bears: 2, food: 'honey' }

const useBearStore = create<BearState>()((set) => ({
  ...initialState,
  feed: (food) => set({ food }),
  increase: (by) => set((state) => ({ bears: state.bears + by })),
  reset: () => set(initialState),
}))

export function TypedBears() {
  const bears = useBearStore((state) => state.bears)
  const food = useBearStore((state) => state.food)
  const feed = useBearStore((state) => state.feed)
  const increase = useBearStore((state) => state.increase)
  const reset = useBearStore((state) => state.reset)

  return (
    <section>
      <h2>Explicit types</h2>
      <p>{bears} bears eating {food}</p>
      <button onClick={() => increase(5)}>Increase by 5</button>
      <button onClick={() => feed('berries')}>Feed berries</button>
      <button onClick={reset}>Reset</button>
    </section>
  )
}
```

![The explicitly typed panel starts with two bears eating honey and offers Increase by 5, Feed berries, and Reset.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/7c27e53e9105b16bb1484e9b861e82d4.png)

The panel starts with two bears eating honey. The buttons change the count or food; Reset restores the initial data. Because `set(initialState)` merges those fields, it retains the actions. TypeScript checks the returned state and infers the action parameters from `BearState`.

## Create without the curried form

When you want inference instead of an explicit state interface, use [`combine`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-middleware#combine). It returns a state creator that merges the initial object with the additional state and actions. Pass it directly to `create(...)`, without the intermediate `()`.

1. Put initial data in the first argument.
2. Return actions from the second argument; annotate their parameters.
3. Use [`ExtractState`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#extractstate) to reuse the resulting state-and-actions type in component props or utilities.

```tsx title="src/InferredBears.tsx"
import { create } from 'zustand'
import type { ExtractState } from 'zustand'
import { combine } from 'zustand/middleware'

const useBearStore = create(
  combine({ bears: 0, food: 'honey' }, (set) => ({
    increase: (by: number) => set((state) => ({ bears: state.bears + by })),
  })),
)

type BearState = ExtractState<typeof useBearStore>

function BearSummary({ bears, food }: Pick<BearState, 'bears' | 'food'>) {
  return <p>{bears} bears eating {food}</p>
}

export function InferredBears() {
  const bears = useBearStore((state) => state.bears)
  const food = useBearStore((state) => state.food)
  const increase = useBearStore((state) => state.increase)

  return (
    <section>
      <h2>Inferred types</h2>
      <BearSummary bears={bears} food={food} />
      <button onClick={() => increase(5)}>Increase by 5</button>
    </section>
  )
}
```

![The inferred panel displays zero bears eating honey and an Increase by 5 button.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/2fb9456cb13b2053d371010c7d758466.png)

This panel starts at zero and adds five bears per click. `BearState` includes both data fields and `increase`; `Pick` selects only the summary's props without redefining those fields.

## Creating a store with inferred types

The same `combine` pattern works with [`createStore`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#createstore), which returns a vanilla store rather than a hook. Consume it through [`useStore`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#usestore) in React.

1. Create the position store in `src/position-store.ts` with an initial position and a `setPosition` action.
2. Select its position and action in the component.
3. Move the pointer inside the sized container to update the red dot.

```ts title="src/position-store.ts"
import { createStore } from 'zustand'
import { combine } from 'zustand/middleware'

const initialState = { position: { x: 20, y: 20 } }

export const positionStore = createStore(
  combine(initialState, (set) => ({
    setPosition: (position: typeof initialState.position) => set({ position }),
  })),
)
```

Add the React component in `src/InferredPosition.tsx`. The entry file at the end mounts it through `App`.

```tsx title="src/InferredPosition.tsx"
import { useId } from 'react'
import { useStore } from 'zustand'
import { positionStore } from './position-store'

export default function InferredPosition() {
  const headingId = useId()
  const position = useStore(positionStore, (state) => state.position)
  const setPosition = useStore(positionStore, (state) => state.setPosition)

  return (
    <section aria-labelledby={headingId}>
      <h2 id={headingId}>Inferred vanilla store</h2>
      <p>Move the pointer inside the box.</p>
      <div
        style={{ position: 'relative', height: 200, border: '1px solid' }}
        onPointerMove={(event) => {
          const bounds = event.currentTarget.getBoundingClientRect()
          setPosition({
            x: event.clientX - bounds.left,
            y: event.clientY - bounds.top,
          })
        }}
      >
        <div
          style={{
            position: 'absolute',
            left: -10,
            top: -10,
            width: 20,
            height: 20,
            borderRadius: '50%',
            background: 'red',
            transform: `translate(${position.x}px, ${position.y}px)`,
            pointerEvents: 'none',
          }}
        />
      </div>
    </section>
  )
}
```

The red dot starts 20 pixels from the container's top and left edges. Pointer movement updates its position. `combine` infers the resulting store type; the action parameter reuses the initial position's type.

## Create the following function: `createSelectors`

Generate one hook per top-level state field when repeated selector expressions become tedious. The hooks include actions, so `store.use.increment()` returns the action rather than executing it.

1. Add this app-owned helper. It enumerates the store's keys once and attaches a typed `use` object.
2. Apply it once to each store, outside component rendering.
3. Call the generated hooks unconditionally inside React components.

```ts title="src/createSelectors.ts"
import { useStore } from 'zustand'
import type { ExtractState, StoreApi } from 'zustand'

export function createSelectors<S extends StoreApi<object>>(store: S) {
  type State = ExtractState<S>
  const selectors = {} as { [K in keyof State]: () => State[K] }

  function addSelector<K extends keyof State>(key: K) {
    selectors[key] = function useField() {
      return useStore(store, (state) => state[key])
    }
  }

  for (const key of Object.keys(store.getState()) as Array<keyof State>) {
    addSelector(key)
  }

  return Object.assign(store, { use: selectors })
}
```

The mapped type preserves each field's return type. The assertions connect the runtime key enumeration to that mapped type. Use this helper with fixed-shape stores whose fields are own, enumerable string keys; it does not generate hooks for symbols, non-enumerable fields, or keys added later.

Both a bound store and a vanilla store expose the API `useStore` consumes. This version uses that hook for both and preserves the original store's type and methods.

```tsx title="src/GeneratedSelectors.tsx"
import { create, createStore } from 'zustand'
import { createSelectors } from './createSelectors'

interface BearState {
  bears: number
  increase: (by: number) => void
  increment: () => void
}

const useBearStoreBase = create<BearState>()((set) => ({
  bears: 0,
  increase: (by) => set((state) => ({ bears: state.bears + by })),
  increment: () => set((state) => ({ bears: state.bears + 1 })),
}))

const vanillaStore = createStore<BearState>()((set) => ({
  bears: 0,
  increase: (by) => set((state) => ({ bears: state.bears + by })),
  increment: () => set((state) => ({ bears: state.bears + 1 })),
}))

const useBearStore = createSelectors(useBearStoreBase)
const useVanillaBearStore = createSelectors(vanillaStore)

export function GeneratedSelectors() {
  const bears = useBearStore.use.bears()
  const increment = useBearStore.use.increment()
  const increase = useBearStore.use.increase()
  const vanillaBears = useVanillaBearStore.use.bears()
  const vanillaIncrement = useVanillaBearStore.use.increment()

  return (
    <section>
      <h2>Generated selectors</h2>
      <p>Bound store: {bears} bears</p>
      <button onClick={increment}>Add one bound bear</button>
      <button onClick={() => increase(5)}>Add five bound bears</button>
      <p>Vanilla store: {vanillaBears} bears</p>
      <button onClick={vanillaIncrement}>Add one vanilla bear</button>
    </section>
  )
}
```

![The generated selectors panel shows separate bound and vanilla counts at zero, with buttons to add bears to each store.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/21924f21a06c72f5abedef2a991c9337.png)

The two counts start at zero and change independently. Each generated hook selects one property from its store. For the authors' selector-generation example, open the [live demo](https://codesandbox.io/s/zustand-auto-generate-selectors-forked-rl8v5e?file=/src/selectors.ts).

## Handling a dynamic `replace` flag

`setState` has separate overloads for merging and replacing. If your replacement flag is a runtime boolean, build the argument tuple using `Parameters<typeof store.setState>` and supply complete state.

1. Read the flag from a checkbox.
2. Include the existing actions in the next state.
3. Spread the typed arguments into `setState` when the user clicks Apply.

```tsx title="src/DynamicReplace.tsx"
import { useState } from 'react'
import { create } from 'zustand'

interface BearState {
  bears: number
  increase: (by: number) => void
}

const useBearStore = create<BearState>()((set) => ({
  bears: 0,
  increase: (by) => set((state) => ({ bears: state.bears + by })),
}))

export function DynamicReplace() {
  const [replace, setReplace] = useState(false)
  const bears = useBearStore((state) => state.bears)
  const increase = useBearStore((state) => state.increase)

  function apply() {
    const nextState: BearState = { ...useBearStore.getState(), bears: 5 }
    const args = [nextState, replace] as Parameters<typeof useBearStore.setState>
    useBearStore.setState(...args)
  }

  return (
    <section>
      <h2>Dynamic replacement</h2>
      <p>{bears} bears</p>
      <label>
        <input
          type="checkbox"
          checked={replace}
          onChange={(event) => setReplace(event.currentTarget.checked)}
        />
        Replace the complete state
      </label>
      <button onClick={apply}>Apply five bears</button>
      <button onClick={() => increase(1)}>Increase by 1</button>
    </section>
  )
}
```

![The dynamic replacement panel starts at zero with an unchecked replacement checkbox, Apply five bears, and Increase by 1.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/c3efec2742d433d50ba19b97d6e76c71.png)

Apply sets the count to five in either mode. Increase remains usable because the supplied state includes the action. The tuple assertion handles overload selection; it does not check that you preserved every field at runtime.

### Replacement options and pitfalls

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `setState` second argument, `replace` | `false` or `true`, depending on the overload | Omitted: shallow merge for non-null object updates; replacement for other values | `false` shallowly merges the update. `true` replaces the entire state. |

Passing `true` discards omitted state, including actions. Supply complete state when replacing, or omit the flag for an object update that preserves other fields. Be especially careful inside `combine`: its initializer's `set` is typed against the initial data, so a replacement containing only that data can compile while removing the actions. The resulting store's `getState()` type includes the data and actions, but the initializer's `get()` type describes only the first argument.

For selectors that compute objects or arrays, continue with [Select computed state](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/select-computed-state). For nested updates, see [Immutable state and merging](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/immutable-state-and-merging).

## Render the examples

Update `src/App.tsx` to render all five panels. Keep the starter's stylesheet import; remove starter-only imports and locals that its previous JSX used so the strict build has no unused declarations.

```tsx title="src/App.tsx"
import './App.css'
import { TypedBears } from './TypedBears'
import { InferredBears } from './InferredBears'
import InferredPosition from './InferredPosition'
import { GeneratedSelectors } from './GeneratedSelectors'
import { DynamicReplace } from './DynamicReplace'

export default function App() {
  return (
    <main>
      <h1>Typed Zustand stores</h1>
      <TypedBears />
      <InferredBears />
      <InferredPosition />
      <GeneratedSelectors />
      <DynamicReplace />
    </main>
  )
}
```

Keep the mounting setup from the [React quick start](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start#4-mount-the-counter) and replace `src/Counter.tsx` with this re-export to display the five panels instead of the counter:

```tsx title="src/Counter.tsx"
export { default } from './App'
```

Run `npm run dev` to open the panels and `npm run build` to check the project. You have explicitly typed state and actions, inferred bound and vanilla stores, reusable extracted types, generated per-field hooks, and a complete-state update controlled by a runtime replacement flag.

## Related

- [Selectors and rendering](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/selectors-and-rendering) explains how selector outputs determine component updates.
- [Split a store into slices](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/split-store-into-slices) shows how to compose a larger typed store.
- [Write typed middleware](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/write-typed-middleware) covers state creators and middleware type transformations.
