The best React state manager

Is it going to be Context, Redux or MobX?

David Minkovski
6 min readSep 10, 2021

--

Motivation

Most react developers understand the importance of local and global state management for a clean architecture and end-user experience.
As developers we want state management to be simple, expandable and clear.
With the hooks update, React has moved into exactly that direction.

But problems can still arise, if the state is to be shared with many components. To do this, developers need to find tools and libraries that meet their needs while meeting high standards required by applications.

In this article I am going to compare the most popular state libraries and choose my personal favorite.

Some Context — Reacts own API

React has an excellent tool to provide data across multiple components.
The primary goal of this so called “Context” is to avoid infinite prop passing. Reacts team wanted to develop a solution that covers the following use cases: frequent updates, restructuring, introduction of new components, etc.

Although all of this can be done with Context, this concept requires very specific and solution-oriented implementation that takes a lot of time. The only advantage of Context is that it does not depend on a third-party library, but that cannot legitimize all the effort involved in using this concept.

In addition, React team member Sebastian Markbage mentioned that the new Context API was not designed nor optimized for frequent updates.

Existing solutions

There are dozen of state management tools (e.g. Redux, MobX, Recoil and Zustand) on GitHub. Taking each one into account would lead to endless research, testing, and comparison. I am sorry but because of this, I’ve narrowed my picks down to the two main competitors based on their popularity, use, and maintenance.
To make the comparison clear, I will consider the following quality features:

  • User friendliness
  • Maintainability
  • Testability
  • Changeability
  • Reusability
  • Community

Redux

Redux is a state technology from 2015. It quickly became popular due to the following factors:
1. There was no serious alternative at the time.
2. It made a separation between state and actions.

React-Redux enabled a direct state connection.
The co-founder of the well-known library is a member of the React core team Dan Abramov.

Source: https://redux.js.org/tutorials/essentials/part-1-overview-concepts

With Redux, the application has a global state / memory in which all data is stored. Whenever the memory needs to be updated, an action is sent to the so-called reducer. Depending on the content of the action type (see graphic Action — “type”), the reducer changes the state.

Code Example

// slices/counter.js
import { createSlice } from "@reduxjs/toolkit";

export const slice = createSlice({
name: "counter",
initialState: {
value: 0
},
reducers: {
plus: (state) => {
state.value += 1;
},
minus: (state) => {
state.value -= 1;
}
}
});

export const actions = slice.actions;
export const reducer = slice.reducer;

// store.js
import { configureStore } from "@reduxjs/toolkit";
import { reducer as counterReducer } from "./slices/counter";

export default configureStore({
reducer: {
counter: counterReducer
}
});



// App.js
import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { actions } from "./slices/counter";

const App = () => {
const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();

return (
<div>
<div>
<button onClick={() => dispatch(actions.plus())}>Plus</button>
<span>{count}</span>
<button onClick={() => dispatch(actions.minus())}>Minus</button>
</div>
</div>
);
};

export default App;
// index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import App from './App'
import store from './store'

ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)

Quality features

User friendliness
Redux gets very easy using react-redux. You create a reducer, define actions and transfer it to the store. Then we access it via hooks in a component.

Maintainability
Redux doesn’t require deep knowledge to be understood.
The entire logic is covered by the reducers.

Testability
Redux consists of pure functions (actions and reducers) and is therefore ideal for unit tests and integration tests.

Scalability
Redux has a global state, which makes scaling difficult. However, there are some libraries that allow the creation of modular reducers and middleware.

Changeability
Customizing Redux is effortless as it supports middleware.

Reusability
Redux is framework-independent, so it is super easy to reuse.

Community
Redux has built a large community with a huge knowledge base. There are over 19,000 answered questions on Stack Overflow.

MobX

MobX is another state library and has 23,000 stars on GitHub.
What sets it apart from Redux is, that it follows the OOP paradigm and uses what are known as observables. MobX is maintained by a group of open source developers.

Source: https://camo.githubusercontent.com/c8e97f5bf3e6908e68b34fd187d97fac599afc4efc2807a3434782285db46357/68747470733a2f2f6d6f62782e6a732e6f72672f6173736574732f666c6f77322e706e67

In MobX we create a JavaScript class with a makeObservable call inside the constructor, which is an observable store (you could also use the @observable decorator). Then we declare the state and methods of the class.
The components “subscribe” to this state.
Then you can access the status, calculated values ​​and actions.
Another essential feature of MobX is its changeability. It allows the status to be updated automatically in case you want to avoid side effects.

Code Example

// stores/counter.js
import { makeAutoObservable } from "mobx";
class CounterStore {
value = 0;
constructor() {
makeAutoObservable(this);
}
plus() {
this.value += 1;
}
minus() {
this.value -= 1;
}
}
export default CounterStore;
// App.js
import React from "react";
import { inject, observer } from "mobx-react";
const App = inject((stores) => ({ counter: stores.counter }))(
observer(({ counter }) => {
return (
<div>
<div>
<button onClick={() => counter.plus()}>Plus</button>
<span>{counter.value}</span>
<button onClick={() => counter.minus()}>Minus</button>
</div>
</div>
);
})
);
export default App;// index.js
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "mobx-react";
import App from "./App";
import CounterStore from "./stores/counter";
ReactDOM.render(
<Provider counter={new CounterStore()}>
<App />
</Provider>,
document.getElementById("root")
);

Quality features

User friendliness
An observable class is the only entry point for state management. It makes using MobX very easy.

Maintainability
Using MobX on a poorly qualified team can easily lead to data consistency problems.

Testability
The stores are simple JavaScript objects with hidden functions. Testing is just as easy as it is for any other JavaScript class.

Scalability
Observable memories are logically divided into classes.
So there are no difficulties in scaling MobX.

Changeability
MobX enables the creation of user-defined observables with their own behavior. That makes MobX very customizable.

Reusability
MobX is framework-independent, so it is very easy to reuse.

Community
There are over 1,000 questions answered with the mobx tag on Stack Overflow.

Summary

MobX and Redux are both big players in the market. What sets them apart is the learning curve. MobX requires a basic understanding of reactive programming. If the developers are not adequately qualified, the application can end up causing code inconsistencies, performance problems, and significantly increased development time.

Redux also has some problems, mostly related to scalability. However, there are well established solutions to these problems.

So, taking into account all the pros and cons and taking into account my personal experience, I definitely recommend Redux as the best option for React applications. Thank you and I hope you enjoyed this article!

Curious about more?

My newsletter is a burst of tech inspiration, problem-solving hacks, and entrepreneurial spirit.
Subscribe for your weekly dose of innovation and mind-freeing insights:
https://davidthetechie.substack.com/

--

--