zustand vs redux vs mobx vs recoil vs react-redux vs redux-saga vs redux-thunk vs xstate
State Management Solutions for React Applications
zustandreduxmobxrecoilreact-reduxredux-sagaredux-thunkxstateSimilar Packages:

State Management Solutions for React Applications

mobx, react-redux, recoil, redux, redux-saga, redux-thunk, xstate, and zustand are all libraries designed to manage application state in JavaScript applications, particularly those built with React. They address the challenge of sharing, synchronizing, and updating data across components while maintaining predictability and performance. redux provides a centralized store with immutable state updates via pure reducer functions. react-redux is the official React binding for Redux, enabling efficient component subscriptions. redux-thunk and redux-saga extend Redux to handle side effects like API calls—thunks with simple async functions, sagas with generator-based control flow. mobx uses observable state and automatic reactivity to track dependencies and update components. recoil offers a graph-based model with atoms (shared state) and selectors (derived state). zustand provides a lightweight, hook-centric store with minimal boilerplate. xstate implements finite state machines and statecharts for modeling complex, deterministic workflows.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
zustand33,503,15357,90995 kB7a month agoMIT
redux33,073,23461,446290 kB422 years agoMIT
mobx3,438,18528,1834.35 MB817 months agoMIT
recoil465,96819,4932.21 MB3223 years agoMIT
react-redux023,483823 kB37a year agoMIT
redux-saga022,4746.25 kB456 months agoMIT
redux-thunk017,71226.8 kB12 years agoMIT
xstate029,5602.28 MB1323 days agoMIT

State Management Deep Dive: MobX, Redux Ecosystem, Recoil, Zustand, and XState Compared

Managing state in React apps goes beyond useState. When data must be shared across components, survive re-renders, or coordinate complex workflows, you need a dedicated solution. The libraries here offer different philosophies: some enforce strict immutability (redux), others embrace reactivity (mobx), while some model behavior explicitly (xstate). Let’s compare them through real engineering lenses.

🧠 Core Philosophy: How Each Library Thinks About State

redux treats state as immutable snapshots. Every change produces a new state object via pure reducer functions. This enables powerful debugging but requires discipline.

// redux: Immutable updates via reducers
const counterReducer = (state = { count: 0 }, action) => {
  switch (action.type) {
    case 'increment':
      return { ...state, count: state.count + 1 };
    default:
      return state;
  }
};

mobx uses observable objects. Changes to state automatically notify observers (like React components), with mutations allowed directly.

// mobx: Mutable state with automatic tracking
import { makeAutoObservable } from 'mobx';

class Counter {
  count = 0;
  constructor() {
    makeAutoObservable(this);
  }
  increment() {
    this.count++; // Direct mutation
  }
}

recoil models state as a directed graph of atoms (units of state) and selectors (computed values). Components subscribe only to what they use.

// recoil: Atoms and selectors
import { atom, selector } from 'recoil';

const countAtom = atom({ key: 'count', default: 0 });
const doubledCount = selector({
  key: 'doubledCount',
  get: ({ get }) => get(countAtom) * 2
});

zustand provides a single store hook with mutable state. No providers, no actions—just a function returning state and setters.

// zustand: Minimal store
import { create } from 'zustand';

const useStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 }))
}));

xstate defines state as explicit machines with finite states and transitions. Behavior is declared upfront, preventing invalid flows.

// xstate: State machine
import { createMachine } from 'xstate';

const toggleMachine = createMachine({
  id: 'toggle',
  initial: 'inactive',
  states: {
    inactive: { on: { TOGGLE: 'active' } },
    active: { on: { TOGGLE: 'inactive' } }
  }
});

⚙️ Side Effects: Handling Async Logic

When your state depends on API calls or timers, how you manage side effects matters.

redux-thunk lets action creators return functions that dispatch actions asynchronously.

// redux-thunk: Simple async
const fetchUser = (id) => async (dispatch) => {
  dispatch({ type: 'FETCH_START' });
  try {
    const user = await api.getUser(id);
    dispatch({ type: 'FETCH_SUCCESS', payload: user });
  } catch (err) {
    dispatch({ type: 'FETCH_ERROR', error: err });
  }
};

redux-saga uses generator functions to describe complex async flows declaratively.

// redux-saga: Complex async with cancellation
import { call, put, takeEvery, cancel } from 'redux-saga/effects';

function* fetchUserSaga(action) {
  const task = yield fork(api.getUser, action.payload.id);
  yield take('CANCEL_FETCH');
  yield cancel(task);
}

function* watchFetchUser() {
  yield takeEvery('FETCH_USER', fetchUserSaga);
}

mobx allows async methods directly in stores, often using async/await.

// mobx: Async in store
import { makeAutoObservable, runInAction } from 'mobx';

class UserStore {
  user = null;
  loading = false;
  constructor() {
    makeAutoObservable(this);
  }
  async fetchUser(id) {
    this.loading = true;
    try {
      const user = await api.getUser(id);
      runInAction(() => {
        this.user = user;
        this.loading = false;
      });
    } catch (err) {
      // handle error
    }
  }
}

recoil supports async selectors that automatically manage loading and error states.

// recoil: Async selector
const userQuery = selector({
  key: 'userQuery',
  get: async ({ get }) => {
    const id = get(userIdAtom);
    const response = await fetch(`/api/user/${id}`);
    return response.json();
  }
});

zustand handles async directly in actions, similar to MobX.

// zustand: Async in store
const useStore = create((set) => ({
  user: null,
  loading: false,
  fetchUser: async (id) => {
    set({ loading: true });
    try {
      const user = await api.getUser(id);
      set({ user, loading: false });
    } catch (err) {
      // handle error
    }
  }
}));

xstate integrates async via invoke and transition guards.

// xstate: Async in machine
const fetchUserMachine = createMachine({
  id: 'fetchUser',
  initial: 'idle',
  context: { user: null },
  states: {
    idle: {
      on: { FETCH: 'loading' }
    },
    loading: {
      invoke: {
        src: 'getUser',
        onDone: { target: 'success', actions: 'assignUser' },
        onError: 'failure'
      }
    },
    success: {},
    failure: {}
  }
}, {
  services: {
    getUser: (context, event) => api.getUser(event.id)
  },
  actions: {
    assignUser: assign({ user: (context, event) => event.data })
  }
});

📦 Integration with React: How You Use It in Components

react-redux requires a <Provider> and uses hooks to connect components.

// react-redux: Component usage
import { useSelector, useDispatch } from 'react-redux';

function Counter() {
  const count = useSelector(state => state.count);
  const dispatch = useDispatch();
  return (
    <button onClick={() => dispatch({ type: 'increment' })}>
      {count}
    </button>
  );
}

mobx uses observer to wrap components, which auto-track used observables.

// mobx: Observer component
import { observer } from 'mobx-react-lite';

const Counter = observer(({ store }) => (
  <button onClick={() => store.increment()}>
    {store.count}
  </button>
));

recoil uses hooks directly—no providers needed in most cases.

// recoil: Hook usage
import { useRecoilState, useRecoilValue } from 'recoil';

function Counter() {
  const [count, setCount] = useRecoilState(countAtom);
  const doubled = useRecoilValue(doubledCount);
  return <div>{doubled}</div>;
}

zustand uses its store hook directly in components.

// zustand: Hook usage
function Counter() {
  const { count, increment } = useStore();
  return <button onClick={increment}>{count}</button>;
}

xstate uses useMachine to instantiate and interact with machines.

// xstate: Hook usage
import { useMachine } from '@xstate/react';

function Toggle() {
  const [state, send] = useMachine(toggleMachine);
  return (
    <button onClick={() => send('TOGGLE')}>
      {state.value === 'active' ? 'ON' : 'OFF'}
    </button>
  );
}

🔍 Developer Experience: Debugging and Tooling

redux shines with the Redux DevTools extension, offering time-travel debugging, action inspection, and state diffing. Middleware like redux-logger adds console logging.

mobx offers mobx-devtools for tracking observables and reactions, though less mature than Redux’s tooling. Strict mode helps catch accidental mutations.

recoil has experimental DevTools that visualize the state graph and dependencies, but adoption is limited due to Meta’s reduced investment.

zustand provides minimal built-in tooling but integrates with Redux DevTools via middleware. Its simplicity often reduces the need for advanced debugging.

xstate includes the XState Inspector for visualizing state machines and transitions, invaluable for complex workflows.

🔄 Mutability vs Immutability: Data Update Strategies

  • Immutable: redux, react-redux, recoil (atoms are replaced, not mutated)
  • Mutable: mobx, zustand (though zustand encourages immutable updates via set)
  • Hybrid: xstate (context can be mutable, but state transitions are immutable)

This choice affects performance, debugging, and mental model. Immutability prevents accidental side effects but requires more careful coding. Mutability feels natural but risks unexpected updates if not managed.

🧩 When to Combine Libraries

These aren’t always mutually exclusive:

  • Use redux + redux-saga for complex enterprise apps needing audit trails.
  • Use xstate for UI workflow logic (e.g., checkout steps) alongside zustand for cached data.
  • Use mobx for local component state and recoil for global config if migrating incrementally.

Avoid mixing too many—each adds cognitive overhead.

📊 Summary Table

LibraryState ModelAsync HandlingReact IntegrationMutabilityBest For
reduxCentralized storeMiddleware (thunk/saga)react-reduxImmutableLarge apps needing strict predictability
react-reduxBinding onlyN/ARequired for ReduxN/AConnecting Redux to React
redux-thunkMiddlewareSimple asyncWith ReduxN/ABasic API calls in Redux apps
redux-sagaMiddlewareComplex asyncWith ReduxN/AAdvanced async workflows in Redux
mobxObservable objectsAsync methodsobserver HOCMutableReactive apps with minimal boilerplate
recoilAtom graphAsync selectorsHooksImmutableFine-grained state with derived data
zustandSingle storeAsync actionsHooksMutable*Lightweight global state without providers
xstateState machinesInvoke/servicesuseMachineHybridExplicit, deterministic UI flows

💡 Final Guidance

  • Start simple: For most new apps, zustand or recoil reduce boilerplate without sacrificing power.
  • Need auditability? Stick with redux and its ecosystem.
  • Modeling complex flows? xstate prevents bugs by design.
  • Prefer reactivity? mobx feels intuitive but requires discipline.
  • Avoid over-engineering: If your app only shares a few values, React Context might suffice.

Choose based on your team’s familiarity, app complexity, and long-term maintenance needs—not hype.

How to Choose: zustand vs redux vs mobx vs recoil vs react-redux vs redux-saga vs redux-thunk vs xstate

  • zustand:

    Choose zustand if you want a minimal, hook-based global state solution with zero boilerplate, no context providers, and excellent performance out of the box. It’s perfect for small-to-medium apps or teams migrating away from Redux who still need shared state. Avoid it if you require advanced dev tools, middleware ecosystems, or strict immutability guarantees.

  • redux:

    Choose redux if you need a predictable, centralized state container with strong dev tools, middleware support, and time-travel debugging. It’s best suited for large applications requiring strict state immutability, auditability, and team-wide consistency. Be aware that it demands more boilerplate and learning overhead compared to newer alternatives.

  • mobx:

    Choose mobx if you prefer a reactive programming model where state changes automatically trigger UI updates without manual subscription management. It’s ideal for teams comfortable with mutable state and seeking to minimize boilerplate, especially in medium-to-large apps where fine-grained reactivity improves performance. However, be prepared to adopt strict mode or use makeAutoObservable to avoid common pitfalls with observability.

  • recoil:

    Choose recoil if you want a modern, React-native approach to global state with built-in support for derived state, async selectors, and concurrent rendering. It works well for apps needing fine-grained updates and data-flow graphs, but note that its future is uncertain as Meta has shifted focus to React Server Components, so consider long-term maintenance risks.

  • react-redux:

    Choose react-redux if you’re already using Redux and need the official, optimized React integration that handles store subscription, memoization, and context efficiently. It’s essential for any Redux-based React app, providing hooks like useSelector and useDispatch. Don’t use it standalone—it’s a binding layer, not a state management solution by itself.

  • redux-saga:

    Choose redux-saga if your Redux app involves complex side effects like long-running tasks, race conditions, or cancellation logic that thunks can’t easily express. It uses ES6 generators to manage control flow declaratively, making testable and maintainable async logic. Only use it alongside redux—it’s not a standalone state manager.

  • redux-thunk:

    Choose redux-thunk if your Redux app needs simple asynchronous logic like basic API calls that dispatch actions based on responses. It’s the easiest Redux middleware to learn and integrates seamlessly with standard Redux patterns. Avoid it for complex workflows involving multiple dependent async operations or cancellation—opt for redux-saga instead.

  • xstate:

    Choose xstate if your application logic is best modeled as explicit state machines or statecharts, such as multi-step wizards, complex UI flows, or protocol-driven interactions. It enforces deterministic transitions and prevents invalid states, improving reliability. It’s not a general-purpose state store—use it for behavior modeling, not data caching.

README for zustand

Build Status Build Size Version Downloads Discord Shield

A small, fast and scalable bearbones state-management solution using simplified flux principles. Has a comfy API based on hooks, isn't boilerplatey or opinionated.

Don't disregard it because it's cute. It has quite the claws, lots of time was spent dealing with common pitfalls, like the dreaded zombie child problem, react concurrency, and context loss between mixed renderers. It may be the one state-manager in the React space that gets all of these right.

You can try a live demo and read the docs.

npm install zustand

:warning: This readme is written for JavaScript users. If you are a TypeScript user, be sure to check out our TypeScript Usage section.

First create a store

Your store is a hook! You can put anything in it: primitives, objects, functions. State has to be updated immutably and the set function merges state to help it.

import { create } from 'zustand'

const useBearStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
}))

Then bind your components, and that's it!

Use the hook anywhere, no providers are needed. Select your state and the component will re-render on changes.

function BearCounter() {
  const bears = useBearStore((state) => state.bears)
  return <h1>{bears} around here ...</h1>
}

function Controls() {
  const increasePopulation = useBearStore((state) => state.increasePopulation)
  return <button onClick={increasePopulation}>one up</button>
}

Why zustand over redux?

Why zustand over context?

  • Less boilerplate
  • Renders components only on changes
  • Centralized, action-based state management

Recipes

Fetching everything

You can, but bear in mind that it will cause the component to update on every state change!

const state = useBearStore()

Selecting multiple state slices

It detects changes with strict-equality (old === new) by default, this is efficient for atomic state picks.

const nuts = useBearStore((state) => state.nuts)
const honey = useBearStore((state) => state.honey)

If you want to construct a single object with multiple state-picks inside, similar to redux's mapStateToProps, you can use useShallow to prevent unnecessary rerenders when the selector output does not change according to shallow equal.

import { create } from 'zustand'
import { useShallow } from 'zustand/react/shallow'

const useBearStore = create((set) => ({
  nuts: 0,
  honey: 0,
  treats: {},
  // ...
}))

// Object pick, re-renders the component when either state.nuts or state.honey change
const { nuts, honey } = useBearStore(
  useShallow((state) => ({ nuts: state.nuts, honey: state.honey })),
)

// Array pick, re-renders the component when either state.nuts or state.honey change
const [nuts, honey] = useBearStore(
  useShallow((state) => [state.nuts, state.honey]),
)

// Mapped picks, re-renders the component when state.treats changes in order, count or keys
const treats = useBearStore(useShallow((state) => Object.keys(state.treats)))

For more control over re-rendering, you may provide any custom equality function (this example requires the use of createWithEqualityFn).

const treats = useBearStore(
  (state) => state.treats,
  (oldTreats, newTreats) => compare(oldTreats, newTreats),
)

Overwriting state

The set function has a second argument, false by default. Instead of merging, it will replace the state model. Be careful not to wipe out parts you rely on, like actions.

const useFishStore = create((set) => ({
  salmon: 1,
  tuna: 2,
  deleteEverything: () => set({}, true), // clears the entire store, actions included
  deleteTuna: () => set(({ tuna, ...rest }) => rest, true),
}))

Async actions

Just call set when you're ready, zustand doesn't care if your actions are async or not.

const useFishStore = create((set) => ({
  fishies: {},
  fetch: async (pond) => {
    const response = await fetch(pond)
    set({ fishies: await response.json() })
  },
}))

Read from state in actions

set allows fn-updates set(state => result), but you still have access to state outside of it through get.

const useSoundStore = create((set, get) => ({
  sound: 'grunt',
  action: () => {
    const sound = get().sound
    ...

Reading/writing state and reacting to changes outside of components

Sometimes you need to access state in a non-reactive way or act upon the store. For these cases, the resulting hook has utility functions attached to its prototype.

:warning: This technique is not recommended for adding state in React Server Components (typically in Next.js 13 and above). It can lead to unexpected bugs and privacy issues for your users. For more details, see #2200.

const useDogStore = create(() => ({ paw: true, snout: true, fur: true }))

// Getting non-reactive fresh state
const paw = useDogStore.getState().paw
// Listening to all changes, fires synchronously on every change
const unsub1 = useDogStore.subscribe(console.log)
// Updating state, will trigger listeners
useDogStore.setState({ paw: false })
// Unsubscribe listeners
unsub1()

// You can of course use the hook as you always would
function Component() {
  const paw = useDogStore((state) => state.paw)
  ...

Using subscribe with selector

If you need to subscribe with a selector, subscribeWithSelector middleware will help.

With this middleware subscribe accepts an additional signature:

subscribe(selector, callback, options?: { equalityFn, fireImmediately }): Unsubscribe
import { subscribeWithSelector } from 'zustand/middleware'
const useDogStore = create(
  subscribeWithSelector(() => ({ paw: true, snout: true, fur: true })),
)

// Listening to selected changes, in this case when "paw" changes
const unsub2 = useDogStore.subscribe((state) => state.paw, console.log)
// Subscribe also exposes the previous value
const unsub3 = useDogStore.subscribe(
  (state) => state.paw,
  (paw, previousPaw) => console.log(paw, previousPaw),
)
// Subscribe also supports an optional equality function
const unsub4 = useDogStore.subscribe(
  (state) => [state.paw, state.fur],
  console.log,
  { equalityFn: shallow },
)
// Subscribe and fire immediately
const unsub5 = useDogStore.subscribe((state) => state.paw, console.log, {
  fireImmediately: true,
})

Using zustand without React

Zustand core can be imported and used without the React dependency. The only difference is that the create function does not return a hook, but the API utilities.

import { createStore } from 'zustand/vanilla'

const store = createStore((set) => ...)
const { getState, setState, subscribe, getInitialState } = store

export default store

You can use a vanilla store with useStore hook available since v4.

import { useStore } from 'zustand'
import { vanillaStore } from './vanillaStore'

const useBoundStore = (selector) => useStore(vanillaStore, selector)

:warning: Note that middlewares that modify set or get are not applied to getState and setState.

Transient updates (for often occurring state-changes)

The subscribe function allows components to bind to a state-portion without forcing re-render on changes. Best combine it with useEffect for automatic unsubscribe on unmount. This can make a drastic performance impact when you are allowed to mutate the view directly.

const useScratchStore = create((set) => ({ scratches: 0, ... }))

const Component = () => {
  // Fetch initial state
  const scratchRef = useRef(useScratchStore.getState().scratches)
  // Connect to the store on mount, disconnect on unmount, catch state-changes in a reference
  useEffect(() => useScratchStore.subscribe(
    state => (scratchRef.current = state.scratches)
  ), [])
  ...

Sick of reducers and changing nested states? Use Immer!

Reducing nested structures is tiresome. Have you tried immer?

import { produce } from 'immer'

const useLushStore = create((set) => ({
  lush: { forest: { contains: { a: 'bear' } } },
  clearForest: () =>
    set(
      produce((state) => {
        state.lush.forest.contains = null
      }),
    ),
}))

const clearForest = useLushStore((state) => state.clearForest)
clearForest()

Alternatively, there are some other solutions.

Persist middleware

You can persist your store's data using any kind of storage.

import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'

const useFishStore = create(
  persist(
    (set, get) => ({
      fishes: 0,
      addAFish: () => set({ fishes: get().fishes + 1 }),
    }),
    {
      name: 'food-storage', // name of the item in the storage (must be unique)
      storage: createJSONStorage(() => sessionStorage), // (optional) by default, 'localStorage' is used
    },
  ),
)

See the full documentation for this middleware.

Immer middleware

Immer is available as middleware too.

import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'

const useBeeStore = create(
  immer((set) => ({
    bees: 0,
    addBees: (by) =>
      set((state) => {
        state.bees += by
      }),
  })),
)

Can't live without redux-like reducers and action types?

const types = { increase: 'INCREASE', decrease: 'DECREASE' }

const reducer = (state, { type, by = 1 }) => {
  switch (type) {
    case types.increase:
      return { grumpiness: state.grumpiness + by }
    case types.decrease:
      return { grumpiness: state.grumpiness - by }
  }
}

const useGrumpyStore = create((set) => ({
  grumpiness: 0,
  dispatch: (args) => set((state) => reducer(state, args)),
}))

const dispatch = useGrumpyStore((state) => state.dispatch)
dispatch({ type: types.increase, by: 2 })

Or, just use our redux-middleware. It wires up your main-reducer, sets the initial state, and adds a dispatch function to the state itself and the vanilla API.

import { redux } from 'zustand/middleware'

const useGrumpyStore = create(redux(reducer, initialState))

Redux devtools

Install the Redux DevTools Chrome extension to use the devtools middleware.

import { devtools } from 'zustand/middleware'

// Usage with a plain action store, it will log actions as "setState"
const usePlainStore = create(devtools((set) => ...))
// Usage with a redux store, it will log full action types
const useReduxStore = create(devtools(redux(reducer, initialState)))

One redux devtools connection for multiple stores

import { devtools } from 'zustand/middleware'

// Usage with a plain action store, it will log actions as "setState"
const usePlainStore1 = create(devtools((set) => ..., { name, store: storeName1 }))
const usePlainStore2 = create(devtools((set) => ..., { name, store: storeName2 }))
// Usage with a redux store, it will log full action types
const useReduxStore1 = create(devtools(redux(reducer, initialState)), { name, store: storeName3 })
const useReduxStore2 = create(devtools(redux(reducer, initialState)), { name, store: storeName4 })

Assigning different connection names will separate stores in redux devtools. This also helps group different stores into separate redux devtools connections.

devtools takes the store function as its first argument, optionally you can name the store or configure serialize options with a second argument.

Name store: devtools(..., {name: "MyStore"}), which will create a separate instance named "MyStore" in the devtools.

Serialize options: devtools(..., { serialize: { options: true } }).

Logging Actions

devtools will only log actions from each separated store unlike in a typical combined reducers redux store. See an approach to combining stores https://github.com/pmndrs/zustand/issues/163

You can log a specific action type for each set function by passing a third parameter:

const useBearStore = create(devtools((set) => ({
  ...
  eatFish: () => set(
    (prev) => ({ fishes: prev.fishes > 1 ? prev.fishes - 1 : 0 }),
    undefined,
    'bear/eatFish'
  ),
  ...

You can also log the action's type along with its payload:

  ...
  addFishes: (count) => set(
    (prev) => ({ fishes: prev.fishes + count }),
    undefined,
    { type: 'bear/addFishes', count, }
  ),
  ...

If an action type is not provided, it is defaulted to "anonymous". You can customize this default value by providing an anonymousActionType parameter:

devtools(..., { anonymousActionType: 'unknown', ... })

If you wish to disable devtools (on production for instance). You can customize this setting by providing the enabled parameter:

devtools(..., { enabled: false, ... })

React context

The store created with create doesn't require context providers. In some cases, you may want to use contexts for dependency injection or if you want to initialize your store with props from a component. Because the normal store is a hook, passing it as a normal context value may violate the rules of hooks.

The recommended method available since v4 is to use the vanilla store.

import { createContext, useContext } from 'react'
import { createStore, useStore } from 'zustand'

const store = createStore(...) // vanilla store without hooks

const StoreContext = createContext()

const App = () => (
  <StoreContext.Provider value={store}>
    ...
  </StoreContext.Provider>
)

const Component = () => {
  const store = useContext(StoreContext)
  const slice = useStore(store, selector)
  ...

TypeScript Usage

Basic typescript usage doesn't require anything special except for writing create<State>()(...) instead of create(...)...

import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'
import type {} from '@redux-devtools/extension' // required for devtools typing

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

const useBearStore = create<BearState>()(
  devtools(
    persist(
      (set) => ({
        bears: 0,
        increase: (by) => set((state) => ({ bears: state.bears + by })),
      }),
      {
        name: 'bear-storage',
      },
    ),
  ),
)

A more detailed TypeScript guide is here and there.

Best practices

Third-Party Libraries

Some users may want to extend Zustand's feature set which can be done using third-party libraries made by the community. For information regarding third-party libraries with Zustand, visit the doc.

Comparison with other libraries