zustand vs mobx vs recoil vs nanostores vs effector
State Management Libraries Comparison
1 Year
zustandmobxrecoilnanostoreseffectorSimilar Packages:
What's State Management Libraries?

State management libraries are essential tools in web development that help manage the state of applications in a predictable and efficient manner. They provide mechanisms to store, update, and retrieve application state, allowing developers to build scalable and maintainable applications. These libraries often offer features such as reactivity, ease of integration with UI frameworks, and support for complex state interactions, making them invaluable for modern web applications.

NPM Package Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
zustand2,427,80648,94188.8 kB525 days agoMIT
mobx817,29827,6444.33 MB642 months agoMIT
recoil315,65919,6352.21 MB3252 years agoMIT
nanostores64,3585,63643.6 kB244 months agoMIT
effector38,2074,6301.42 MB1653 months agoMIT
Feature Comparison: zustand vs mobx vs recoil vs nanostores vs effector

Reactivity

  • zustand:

    Zustand provides a simple and intuitive API for creating stores that are reactive. It allows components to subscribe to specific slices of state, ensuring that they only re-render when the relevant state changes.

  • mobx:

    MobX employs observable state and reactions to automatically update the UI when the state changes. This makes it easy to work with complex data structures and ensures that the UI stays in sync with the underlying state without manual intervention.

  • recoil:

    Recoil introduces a novel approach to state management in React by allowing atoms (units of state) to be shared across components. This enables fine-grained reactivity, where only the components that use a specific atom will re-render when that atom's state changes.

  • nanostores:

    Nanostores offers a reactive API that allows for easy subscription to state changes. It is designed to be minimalistic, providing a straightforward way to manage state without the overhead of more complex libraries.

  • effector:

    Effector provides a highly reactive architecture that allows for fine-grained updates. It uses stores and events to manage state changes, ensuring that only the components that depend on the changed state are re-rendered, leading to optimal performance.

Learning Curve

  • zustand:

    Zustand is known for its simplicity, making it one of the easiest state management libraries to learn. Its straightforward API allows developers to quickly implement state management without extensive documentation.

  • mobx:

    MobX is relatively easy to learn, especially for those familiar with object-oriented programming. Its automatic reactivity reduces the need for boilerplate code, making it accessible for beginners.

  • recoil:

    Recoil has a gentle learning curve for React developers, as it builds on familiar concepts like atoms and selectors. Its integration with React's ecosystem makes it intuitive for those already accustomed to React's paradigms.

  • nanostores:

    Nanostores is designed to be simple and straightforward, making it easy to pick up for developers of all skill levels. Its minimalistic approach means less time spent on learning and more time on building features.

  • effector:

    Effector has a moderate learning curve due to its unique concepts like stores, events, and effects. However, once understood, it offers powerful capabilities for managing complex state interactions.

Performance

  • zustand:

    Zustand is highly performant due to its minimalistic approach. It allows for direct state updates without the need for complex subscriptions, ensuring quick and efficient reactivity.

  • mobx:

    MobX is designed for high performance with its fine-grained reactivity. It minimizes unnecessary re-renders by tracking dependencies automatically, ensuring that only the components that rely on changed state are updated.

  • recoil:

    Recoil is built with performance in mind, leveraging React's concurrent mode to optimize rendering. It allows for efficient state management with minimal performance overhead, making it ideal for complex applications.

  • nanostores:

    Nanostores is lightweight and performs exceptionally well in small to medium-sized applications. Its minimalistic design leads to low overhead and fast state updates, making it suitable for performance-critical applications.

  • effector:

    Effector is optimized for performance, allowing for efficient state updates and minimal re-renders. Its architecture ensures that only the necessary components are updated, resulting in fast and responsive applications.

Extensibility

  • zustand:

    Zustand is inherently extensible, allowing developers to create custom hooks and middleware to enhance state management capabilities. Its straightforward API facilitates easy integration with other libraries.

  • mobx:

    MobX can be extended with decorators and custom observable types, allowing for a high degree of customization. This makes it adaptable to various programming styles and application requirements.

  • recoil:

    Recoil supports extensibility through its atom and selector architecture, enabling developers to create complex state management solutions that can be easily integrated into React applications.

  • nanostores:

    Nanostores is designed to be lightweight and extensible, allowing developers to integrate it easily with other libraries and frameworks. Its simplicity encourages developers to build custom solutions as needed.

  • effector:

    Effector is highly extensible, allowing developers to create custom stores and effects that can be tailored to specific application needs. This flexibility makes it suitable for a wide range of applications.

Community and Ecosystem

  • zustand:

    Zustand has a vibrant community and is increasingly popular among React developers. Its simplicity and ease of use have led to a growing number of tutorials and resources available online.

  • mobx:

    MobX boasts a mature community with extensive documentation and a wealth of resources. It has been widely adopted in many projects, ensuring a robust ecosystem for support and collaboration.

  • recoil:

    Recoil is backed by Facebook and has a rapidly growing community. Its integration with React ensures a strong ecosystem, with many resources and libraries being developed around it.

  • nanostores:

    Nanostores is relatively new but is gaining traction due to its simplicity and performance. The community is growing, and resources are becoming more available as adoption increases.

  • effector:

    Effector has a growing community and ecosystem, with increasing adoption in the industry. Its documentation is comprehensive, and there are various resources available for learning and troubleshooting.

How to Choose: zustand vs mobx vs recoil vs nanostores vs effector
  • zustand:

    Choose Zustand for its simplicity and ease of use, especially if you want a minimalistic approach to state management in React applications. It allows for quick setup and straightforward state management without the complexity of larger libraries.

  • mobx:

    Select MobX if you prefer a simple and intuitive approach to state management with automatic reactivity. It is ideal for applications where you want to minimize boilerplate code and enjoy a more object-oriented style of programming.

  • recoil:

    Use Recoil if you are working with React and need a state management library that offers a simple API and powerful features like derived state and asynchronous queries. It integrates seamlessly with React's concurrent mode, making it suitable for modern React applications.

  • nanostores:

    Opt for Nanostores if you need a lightweight and minimalistic state management solution that is easy to integrate into existing projects. It is perfect for small to medium-sized applications where simplicity and performance are key.

  • effector:

    Choose Effector if you need a highly efficient and flexible state management solution that emphasizes performance and type safety. It is particularly useful for large applications where fine-grained control over state updates is required.

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 here.

npm i 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.

import omit from 'lodash-es/omit'

const useFishStore = create((set) => ({
  salmon: 1,
  tuna: 2,
  deleteEverything: () => set({}, true), // clears the entire store, actions included
  deleteTuna: () => set((state) => omit(state, ['tuna']), 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 useReduxStore = create(devtools(redux(reducer, initialState)), , { name, store: storeName3 })
const useReduxStore = 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 complete TypeScript guide is here.

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