Skip to content
D
Documentation

Organize store actions

how-to
4 min readUpdated

Keep actions beside their state, move them into separate modules, or route updates through a reducer. Use these patterns when several components need the same update logic.

A store holds state independently of React. The recommended pattern is one store for application-wide state, with actions colocated alongside the data they update. Reducers and dispatched actions are optional. For a larger store, keep that organization and split it into slices.

Start in the project from the React quick start. The examples below add files to that project and render together in one page. If you have not installed Zustand, run:

bash
npm install zustand

Read from state in actions

  1. Colocate data and actions with create, and add a describe action that combines the current count and text into a message; see Update and reset state for the basics of set and get.
ts
import { create } from 'zustand'

type ActionState = {
  count: number
  text: string
  message: string
  pending: boolean
  inc: () => void
  setText: (text: string) => void
  describe: () => void
  loadText: () => Promise<void>
}

export const useActionStore = create<ActionState>()((set, get) => ({
  count: 0,
  text: 'hello',
  message: 'Ready',
  pending: false,
  inc: () => set((state) => ({ count: state.count + 1 })),
  setText: (text) => set({ text }),
  describe: () => {
    const { count, text } = get()
    set({ message: `${text}: ${count}` })
  },
  loadText: async () => {
    if (get().pending) return
    set({ pending: true, message: 'Loading' })
    try {
      const response = await fetch('https://api.example.com/message')
      if (!response.ok) throw new Error(`HTTP ${response.status}`)
      const text = await response.text()
      set({ text, message: 'Loaded' })
    } catch (error) {
      set({ message: error instanceof Error ? error.message : 'Request failed' })
    } finally {
      set({ pending: false })
    }
  },
}))

set shallowly merges each update, preserving the other fields and actions, and notifies subscribers. get() returns the current state at the time you call it.

Define initial values directly. Calling get() synchronously while creating the initial state returns undefined and can throw even when TypeScript accepts the code. Read through get only inside actions called after initialization, as describe does here.

  1. Add a component that selects the data and actions separately.
tsx
import { useActionStore } from './action-store'

export default function StateActions() {
  const count = useActionStore((state) => state.count)
  const text = useActionStore((state) => state.text)
  const message = useActionStore((state) => state.message)
  const pending = useActionStore((state) => state.pending)
  const inc = useActionStore((state) => state.inc)
  const setText = useActionStore((state) => state.setText)
  const describe = useActionStore((state) => state.describe)
  const loadText = useActionStore((state) => state.loadText)

  return (
    <section>
      <h2>Colocated actions</h2>
      <p>Count: {count}</p>
      <button type="button" onClick={inc}>+1</button>
      <label>
        Text
        <input value={text} disabled={pending}
          onChange={(event) => setText(event.currentTarget.value)} />
      </label>
      <button type="button" onClick={describe}>Describe current state</button>
      <button type="button" disabled={pending} onClick={() => void loadText()}>
        Load text
      </button>
      <p aria-live="polite">{message}</p>
    </section>
  )
}

After you mount the page below, click +1, edit Text, then click Describe current state. The message contains the current text and count, not a snapshot captured during initialization.

Perform asynchronous updates

  1. In loadText above, replace https://api.example.com/message with your own endpoint that returns plain text and permits requests from your browser app.
  2. Click Load text in the mounted component. The action sets pending before the request, awaits the response, and calls set with the returned text. No asynchronous middleware is required: call set when the result is ready.

The action returns Promise<void>. The component displays Loading during the request, then Loaded or an error message. Inspect the text returned by your own endpoint rather than expecting a particular response body. The button and input stay disabled while pending is true; their state follows store selectors, not local click-handler flags.

Updating state with no store actions

  1. Add a data-only store and export the update functions at module level. These functions call setState; callers do not need to call a React hook to invoke them.
ts
import { create } from 'zustand'

type ExternalState = {
  count: number
  text: string
}

export const useExternalStore = create<ExternalState>()(() => ({
  count: 0,
  text: 'hello',
}))

export const inc = () =>
  useExternalStore.setState((state) => ({ count: state.count + 1 }))

export const setText = (text: string) => useExternalStore.setState({ text })
  1. Import the actions directly into a component. Keep using the store hook for reactive reads.
tsx
import { inc, setText, useExternalStore } from './external-actions'

export default function ExternalActions() {
  const count = useExternalStore((state) => state.count)
  const text = useExternalStore((state) => state.text)

  return (
    <section>
      <h2>External actions</h2>
      <p>Count: {count}</p>
      <button type="button" onClick={inc}>+1</button>
      <label>
        Text
        <input value={text}
          onChange={(event) => setText(event.currentTarget.value)} />
      </label>
      <p>{text}</p>
    </section>
  )
}

Click +1 to increase this store's displayed count; edit Text to update the paragraph. The state contains only count and text. Module-level actions also facilitate code splitting, while colocated actions keep the store self-contained.

Update state through actions and reducers

Use a pure reducer when you want named action objects to describe updates. This example edits a person's first name, last name, and email, following the middleware reference's form example.

  1. Add the reducer and initial state. The union describes your application's action objects, not a copy of a Zustand type.
ts
export type PersonState = {
  firstName: string
  lastName: string
  email: string
}

export type PersonAction =
  | { type: 'person/setFirstName'; firstName: string }
  | { type: 'person/setLastName'; lastName: string }
  | { type: 'person/setEmail'; email: string }

export const initialPerson: PersonState = {
  firstName: 'Barbara',
  lastName: 'Hepworth',
  email: 'bhepworth@sculpture.com',
}

export function personReducer(state: PersonState, action: PersonAction): PersonState {
  switch (action.type) {
    case 'person/setFirstName':
      return { ...state, firstName: action.firstName }
    case 'person/setLastName':
      return { ...state, lastName: action.lastName }
    case 'person/setEmail':
      return { ...state, email: action.email }
    default:
      return state
  }
}
  1. Choose how to wire dispatch. A custom store action can call set((state) => reducer(state, action)). Alternatively, redux takes the reducer and initial state and returns a state creator. It adds dispatch both to state and to the store API; that method returns the dispatched action.

The following module defines both variants for comparison. createStore creates the middleware example's vanilla store.

ts
import { create, createStore } from 'zustand'
import { redux } from 'zustand/middleware'
import { initialPerson, personReducer } from './person-reducer'
import type { PersonAction, PersonState } from './person-reducer'

type ManualPersonState = PersonState & {
  dispatch: (action: PersonAction) => void
}

export const useManualPerson = create<ManualPersonState>()((set) => ({
  ...initialPerson,
  dispatch: (action) => set((state) => personReducer(state, action)),
}))

export const personStore = createStore(redux(personReducer, initialPerson))
  1. Bind the vanilla store to React with useStore. The form calls the store API's dispatch; the button calls the dispatch in state. The separate manual-dispatch example uses the same reducer without middleware.
tsx
import { useStore } from 'zustand'
import { personStore, useManualPerson } from './person-stores'

export default function ReducerActions() {
  const firstName = useStore(personStore, (state) => state.firstName)
  const lastName = useStore(personStore, (state) => state.lastName)
  const email = useStore(personStore, (state) => state.email)
  const dispatch = useStore(personStore, (state) => state.dispatch)
  const manualFirstName = useManualPerson((state) => state.firstName)
  const manualDispatch = useManualPerson((state) => state.dispatch)

  return (
    <section>
      <h2>Reducer actions</h2>
      <label>
        First name
        <input value={firstName} onChange={(event) => personStore.dispatch({
          type: 'person/setFirstName', firstName: event.currentTarget.value,
        })} />
      </label>
      <label>
        Last name
        <input value={lastName} onChange={(event) => personStore.dispatch({
          type: 'person/setLastName', lastName: event.currentTarget.value,
        })} />
      </label>
      <label>
        Email
        <input value={email} onChange={(event) => personStore.dispatch({
          type: 'person/setEmail', email: event.currentTarget.value,
        })} />
      </label>
      <p>{firstName} {lastName} ({email})</p>
      <button type="button" onClick={() => dispatch({
        type: 'person/setFirstName', firstName: 'Ada',
      })}>Set first name to Ada</button>
      <p>Manual dispatch first name: {manualFirstName}</p>
      <button type="button" onClick={() => manualDispatch({
        type: 'person/setFirstName', firstName: 'Ada',
      })}>Dispatch without middleware</button>
    </section>
  )
}

Editing any input updates the corresponding field and the summary. Set first name to Ada changes the middleware store's first name; Dispatch without middleware changes the separate manual store. In your application, choose one wiring style rather than maintaining duplicate stores for the same data. Keep side effects such as HTTP requests outside the pure reducer.

Call an action outside a React event handler

In code written for React before 18, wrap external callbacks' updates in unstable_batchedUpdates from react-dom (or react-native on that platform). This groups updates that older React otherwise processes synchronously outside React event handlers, avoiding the zombie-child effect. Zustand 5 requires React 18 or later; the following browser example shows the callback shape in the current project's React DOM environment.

  1. Add a component that schedules an action from a timer. The callback reads the action through getState(), without calling a hook outside a component.
tsx
import { useEffect } from 'react'
import { unstable_batchedUpdates } from 'react-dom'
import { useStore } from 'zustand'
import { useActionStore } from './action-store'

export default function CallbackActions() {
  const count = useStore(useActionStore, (state) => state.count)

  useEffect(() => {
    const timer = window.setTimeout(() => {
      unstable_batchedUpdates(() => {
        useActionStore.getState().inc()
      })
    }, 1000)
    return () => window.clearTimeout(timer)
  }, [])

  return (
    <p>A timer adds one to the colocated count after one second. Count: {count}</p>
  )
}
The timer component displays its callback hint and the colocated store's count, shown as 1.
  1. Mount all the examples. Add this component, then change only the component import and JSX in the quick start's src/main.tsx: import ActionsExample from ./ActionsExample.tsx and render <ActionsExample /> instead of <Counter />. Keep StrictMode, createRoot, and the stylesheet import intact.
tsx
import StateActions from './StateActions'
import ExternalActions from './ExternalActions'
import ReducerActions from './ReducerActions'
import CallbackActions from './CallbackActions'

export default function ActionsExample() {
  return (
    <main style={{ minHeight: 400, display: 'grid', gap: 24 }}>
      <h1>Store actions</h1>
      <StateActions />
      <ExternalActions />
      <ReducerActions />
      <CallbackActions />
    </main>
  )
}

Run npm run build, then npm run dev. The page renders the colocated controls, external controls, and person form. After one second, the timer increments the colocated count. Unmounting the component cancels a pending timer.

Choose an action pattern

These are organization choices, not configuration options with defaults.

PatternWhere updates liveWhat you get
Colocated actionsFunctions in state, calling set and getA self-contained store with data and its update logic together; the recommended pattern.
External actionsModule functions calling setStateDirect imports for callers and support for code splitting.
Manual dispatchA store action calling a reducer inside setAction objects without middleware.
redux middlewareA reducer passed with initial stateInitialization and dispatch on both state and the store API.

For nested data, follow Immutable state and merging. For action tracing, continue with Debug store actions. Compare the colocated counter with the live Zustand demo.

Was this page helpful?