MobX is the best and most easy way of implementing a store in react project, it is so simple that you will never use redux in your life again. Unless you are told to do so at gunpoint.
There are two ways of implementing MobX one using decorators and the other without it. However MobX for now has moved away from decorators in version 6+, nor it supports backward compatibility for it.
This is something to keep in mind before implementing MobX. In case you want to implement decorators you need to use earlier verison of mobx and react-mobx library.
There are three steps involved in implementing MobX, i.e one creating a store, second making the store available across project, and lastly making components react to store change.
Step 1: Create Store
Below is the code for a simple store, note that we are making use of ‘makeAutoObservable’ which makes all class level variables in store automatically observables. Thus avoiding decorators, also decorators are not supported explicitly in react, you need to make it work with a lot of workarounds.
import { makeAutoObservable } from 'mobx';
class Timer {
secondsPassed = 0;
constructor() {
makeAutoObservable(this);
}
increaseTimer() {
this.secondsPassed += 1;
}
}
export default Timer;
Step 2: Pass Store
The store is passed using React context, simple and easy, earlier version of MobX used to inject store using the react-mobx library. You can refer to my context post in case you are unaware of its implementation.
import React from 'react';
const StoreContext = React.createContext();
export default StoreContext;
import React from 'react';
import ReactDOM from 'react-dom';
import TimerStore from './store/';
import StoreContext from './StoreContext';
import App from './App';
const timerStore = new TimerStore();
ReactDOM.render(
<StoreContext.Provider value={{ timerStore: timerStore }}>
<App />
</StoreContext.Provider>,
document.body
);
setInterval(() => {
timerStore.increaseTimer();
}, 1000);
Step 3: Use Store
Get the store object using useContext hook in case of a functional component or use the Consumer component in the case of class component.
Now your component needs to react to store change and for that, you need to make the component observe store change, which is done using observer from mobx-react-lite.
import React from 'react';
import './style.css';
import StoreContext from './StoreContext';
import { observer } from 'mobx-react-lite';
function App() {
const { timerStore } = React.useContext(StoreContext);
return (
<div>
<h1>Count</h1>
{timerStore.secondsPassed}
</div>
);
}
export default observer(App);
You can refer to this example at StackBlitz. Done !! happy coding