redux vs mobx vs recoil
State Management Libraries Comparison
3 Years
reduxmobxrecoilSimilar Packages:
What's State Management Libraries?

State management libraries in JavaScript help manage and centralize the state of an application, making it easier to share data between components, handle complex state logic, and maintain a predictable state across the app. These libraries provide tools and patterns for managing state efficiently, improving code organization, and enhancing the scalability of applications. redux is a predictable state container for JavaScript apps, mobx is a simple, scalable state management library that uses observables, and recoil is a state management library for React that provides a more flexible and efficient way to manage state with atoms and selectors.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
redux15,009,343
61,328290 kB452 years agoMIT
mobx2,093,326
28,0384.33 MB786 months agoMIT
recoil516,106
19,5862.21 MB3233 years agoMIT
Feature Comparison: redux vs mobx vs recoil

State Management Model

  • redux:

    Redux uses a centralized store with a single source of truth, where the entire application state is stored in one immutable object. State changes are made through pure functions called reducers, which take the current state and an action as arguments and return a new state. This model enforces a strict unidirectional data flow, making state changes predictable and traceable.

  • mobx:

    MobX uses a decentralized and reactive state management model, where state is stored in observable objects that can be mutated directly. Components automatically re-render when they access observable data, thanks to MobX's fine-grained reactivity system. This model allows for more flexible and intuitive state management, as developers can update state directly without needing to dispatch actions or write reducers.

  • recoil:

    Recoil introduces a more granular state management model for React applications, where state is divided into atoms (units of state) and selectors (functions that derive state). Atoms can be read and written from any component, while selectors can compute derived state and can also be asynchronous. This model allows for better performance and scalability, as components only re-render when the specific atoms or selectors they depend on change.

Boilerplate Code

  • redux:

    Redux is known for its boilerplate code, especially when setting up actions, reducers, and the store. Developers often need to write a significant amount of code to handle simple state changes, which can be time-consuming and cumbersome. However, tools like Redux Toolkit have been introduced to reduce boilerplate and simplify the setup process.

  • mobx:

    MobX has minimal boilerplate compared to Redux. Developers can create observable state with just a few lines of code, and there is no need to write actions or reducers. This simplicity makes MobX a more developer-friendly option for managing state, especially in smaller to medium-sized applications.

  • recoil:

    Recoil also aims to minimize boilerplate, especially when working with atoms and selectors. The API is designed to be simple and intuitive, allowing developers to define state and derived values without the need for extensive setup. This makes Recoil a good choice for React developers looking for a more streamlined approach to state management.

Integration with React

  • redux:

    Redux can be integrated with React using the react-redux library, which provides components and hooks (like useSelector and useDispatch) to connect React components to the Redux store. While Redux works well with React, it is not limited to it and can be used with any JavaScript framework or library.

  • mobx:

    MobX integrates seamlessly with React, allowing components to automatically re-render when they access observable state. The mobx-react library provides tools like the observer higher-order component and the observer function to make React components reactive with minimal effort. MobX is particularly well-suited for React applications due to its fine-grained reactivity and simplicity.

  • recoil:

    Recoil is designed specifically for React and leverages its concurrent features for better performance. It provides a simple API for managing state with atoms and selectors, making it easy to integrate into React components. Recoil's design allows for more efficient updates and re-renders, making it a great choice for modern React applications.

Performance

  • redux:

    Redux performance can be impacted by unnecessary re-renders, especially if components are not properly optimized. Since Redux uses a single store, any state change can trigger re-renders in all components that are connected to the store. However, performance can be improved by using techniques like memoization, React.memo, and useSelector with shallow equality checks.

  • mobx:

    MobX is highly performant due to its fine-grained reactivity. Only the components that use the specific observable data that changed will re-render, minimizing unnecessary updates. This makes MobX particularly efficient for applications with complex state and many components, as it reduces the amount of work done during re-renders.

  • recoil:

    Recoil offers good performance, especially with its selective re-rendering model. Components only re-render when the atoms or selectors they depend on change, which helps reduce unnecessary updates. Recoil is designed to handle large component trees efficiently, making it a suitable choice for performance-sensitive React applications.

Ease of Use: Code Examples

  • redux:

    Simple counter example with redux

    import { createStore } from 'redux';
    import { Provider, useDispatch, useSelector } from 'react-redux';
    import React from 'react';
    import ReactDOM from 'react-dom';
    
    // Redux reducer
    const counterReducer = (state = 0, action) => {
      switch (action.type) {
        case 'INCREMENT':
          return state + 1;
        case 'DECREMENT':
          return state - 1;
        default:
          return state;
      }
    };
    
    // Create Redux store
    const store = createStore(counterReducer);
    
    // React components
    const Counter = () => {
      const count = useSelector((state) => state);
      const dispatch = useDispatch();
    
      return (
        <div>
          <h1>{count}</h1>
          <button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
          <button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
        </div>
      );
    };
    
    const App = () => (
      <Provider store={store}>
        <Counter />
      </Provider>
    );
    
    ReactDOM.render(<App />, document.getElementById('root'));
    
  • mobx:

    Simple counter example with mobx

    import { makeAutoObservable } from 'mobx';
    import { observer } from 'mobx-react';
    import React from 'react';
    import ReactDOM from 'react-dom';
    
    // MobX store
    class CounterStore {
      count = 0;
    
      constructor() {
        makeAutoObservable(this);
      }
    
      increment() {
        this.count++;
      }
    
      decrement() {
        this.count--;
      }
    }
    
    const counterStore = new CounterStore();
    
    // React components
    const Counter = observer(() => (
      <div>
        <h1>{counterStore.count}</h1>
        <button onClick={() => counterStore.increment()}>+</button>
        <button onClick={() => counterStore.decrement()}>-</button>
      </div>
    ));
    
    const App = () => <Counter />;
    
    ReactDOM.render(<App />, document.getElementById('root'));
    
  • recoil:

    Simple counter example with recoil

    import React from 'react';
    import ReactDOM from 'react-dom';
    import { atom, useRecoilState, RecoilRoot } from 'recoil';
    
    // Recoil atom
    const countState = atom({
      key: 'countState', // unique ID (with respect to other atoms/selectors)
      default: 0, // default value (aka initial value)
    });
    
    // React components
    const Counter = () => {
      const [count, setCount] = useRecoilState(countState);
    
      return (
        <div>
          <h1>{count}</h1>
          <button onClick={() => setCount(count + 1)}>+</button>
          <button onClick={() => setCount(count - 1)}>-</button>
        </div>
      );
    };
    
    const App = () => (
      <RecoilRoot>
        <Counter />
      </RecoilRoot>
    );
    
    ReactDOM.render(<App />, document.getElementById('root'));
    
How to Choose: redux vs mobx vs recoil
  • redux:

    Choose redux if you need a predictable state container with a strict unidirectional data flow, time travel debugging, and a large ecosystem of middleware and tools. It is ideal for large applications with complex state management needs.

  • mobx:

    Choose mobx if you prefer a more reactive and less boilerplate-heavy approach to state management. It is great for applications where you want to minimize the amount of code needed to manage state and prefer automatic updates of components when the state changes.

  • recoil:

    Choose recoil if you are building a React application and need a more fine-grained and flexible state management solution that integrates seamlessly with React's concurrent features. It is suitable for apps that require a more modern approach to state management with better performance for large component trees.

README for redux

Redux Logo

Redux is a predictable state container for JavaScript apps.

It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger.

You can use Redux together with React, or with any other view library. The Redux core is tiny (2kB, including dependencies), and has a rich ecosystem of addons.

Redux Toolkit is our official recommended approach for writing Redux logic. It wraps around the Redux core, and contains packages and functions that we think are essential for building a Redux app. Redux Toolkit builds in our suggested best practices, simplifies most Redux tasks, prevents common mistakes, and makes it easier to write Redux applications.

GitHub Workflow Status npm version npm downloads redux channel on discord

Installation

Create a React Redux App

The recommended way to start new apps with React and Redux Toolkit is by using our official Redux Toolkit + TS template for Vite, or by creating a new Next.js project using Next's with-redux template.

Both of these already have Redux Toolkit and React-Redux configured appropriately for that build tool, and come with a small example app that demonstrates how to use several of Redux Toolkit's features.

# Vite with our Redux+TS template
# (using the `degit` tool to clone and extract the template)
npx degit reduxjs/redux-templates/packages/vite-template-redux my-app

# Next.js using the `with-redux` template
npx create-next-app --example with-redux my-app

We do not currently have official React Native templates, but recommend these templates for standard React Native and for Expo:

  • https://github.com/rahsheen/react-native-template-redux-typescript
  • https://github.com/rahsheen/expo-template-redux-typescript
npm install @reduxjs/toolkit react-redux

For the Redux core library by itself:

npm install redux

For more details, see the Installation docs page.

Documentation

The Redux core docs are located at https://redux.js.org, and include the full Redux tutorials, as well usage guides on general Redux patterns:

The Redux Toolkit docs are available at https://redux-toolkit.js.org, including API references and usage guides for all of the APIs included in Redux Toolkit.

Learn Redux

Redux Essentials Tutorial

The Redux Essentials tutorial is a "top-down" tutorial that teaches "how to use Redux the right way", using our latest recommended APIs and best practices. We recommend starting there.

Redux Fundamentals Tutorial

The Redux Fundamentals tutorial is a "bottom-up" tutorial that teaches "how Redux works" from first principles and without any abstractions, and why standard Redux usage patterns exist.

Help and Discussion

The #redux channel of the Reactiflux Discord community is our official resource for all questions related to learning and using Redux. Reactiflux is a great place to hang out, ask questions, and learn - please come and join us there!

Before Proceeding Further

Redux is a valuable tool for organizing your state, but you should also consider whether it's appropriate for your situation. Please don't use Redux just because someone said you should - instead, please take some time to understand the potential benefits and tradeoffs of using it.

Here are some suggestions on when it makes sense to use Redux:

  • You have reasonable amounts of data changing over time
  • You need a single source of truth for your state
  • You find that keeping all your state in a top-level component is no longer sufficient

Yes, these guidelines are subjective and vague, but this is for a good reason. The point at which you should integrate Redux into your application is different for every user and different for every application.

For more thoughts on how Redux is meant to be used, please see:

Basic Example

The whole global state of your app is stored in an object tree inside a single store. The only way to change the state tree is to create an action, an object describing what happened, and dispatch it to the store. To specify how state gets updated in response to an action, you write pure reducer functions that calculate a new state based on the old state and the action.

Redux Toolkit simplifies the process of writing Redux logic and setting up the store. With Redux Toolkit, the basic app logic looks like:

import { createSlice, configureStore } from '@reduxjs/toolkit'

const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0
  },
  reducers: {
    incremented: state => {
      // Redux Toolkit allows us to write "mutating" logic in reducers. It
      // doesn't actually mutate the state because it uses the Immer library,
      // which detects changes to a "draft state" and produces a brand new
      // immutable state based off those changes
      state.value += 1
    },
    decremented: state => {
      state.value -= 1
    }
  }
})

export const { incremented, decremented } = counterSlice.actions

const store = configureStore({
  reducer: counterSlice.reducer
})

// Can still subscribe to the store
store.subscribe(() => console.log(store.getState()))

// Still pass action objects to `dispatch`, but they're created for us
store.dispatch(incremented())
// {value: 1}
store.dispatch(incremented())
// {value: 2}
store.dispatch(decremented())
// {value: 1}

Redux Toolkit allows us to write shorter logic that's easier to read, while still following the original core Redux behavior and data flow.

Logo

You can find the official logo on GitHub.

Change Log

This project adheres to Semantic Versioning. Every release, along with the migration instructions, is documented on the GitHub Releases page.

License

MIT