Skip to main content

MobX in React

MobX is a powerful state management library for React that makes it easy to manage and synchronize application state. In this tutorial, we'll learn how to set up MobX in a React app, create observable state, actions, and use the observer to react to state changes.

Installing MobX and MobX-React​

First, let's install the necessary packages:

npm install mobx mobx-react-lite

Creating a MobX Store​

To create a MobX store, we'll define a class with observable properties, actions, and computed values:

JavaScript
import { makeAutoObservable } from 'mobx';

class CounterStore {
count = 0;

constructor() {
makeAutoObservable(this);
}

increment() {
this.count++;
}

decrement() {
this.count--;
}
}

const counterStore = new CounterStore();

export default counterStore;

In this example, we've created a simple counter store that increments or decrements the state using actions.

Creating a MobX Provider​

To make the MobX store available to our React components, we can use the MobXProviderContext from the mobx-react-lite package:

JavaScript
import React from 'react';
import { MobXProviderContext } from 'mobx-react-lite';
import counterStore from './counterStore';
import Counter from './Counter';

function App() {
return (
<MobXProviderContext.Provider value={{ counterStore }}>
<Counter />
</MobXProviderContext.Provider>
);
}

export default App;

Connecting Components to the MobX Store​

Now let's connect our Counter component to the MobX store using the useContext and observer from the mobx-react-lite package:

JavaScript
import React, { useContext } from 'react';
import { observer } from 'mobx-react-lite';
import { MobXProviderContext } from 'mobx-react-lite';

const Counter = observer(() => {
const { counterStore } = useContext(MobXProviderContext);

return (
<div>
<h1>{counterStore.count}</h1>
<button onClick={() => counterStore.increment()}>+</button>
<button onClick={() => counterStore.decrement()}>-</button>
</div>
);
});

export default Counter;

In this example, we've used the useContext hook to access the counter store and the observer function to make our component react to state changes.

Conclusion​

In this tutorial, we've learned how to use MobX for state management in React applications. We've set up a MobX store with observable state and actions and connected our React components to the MobX store using the mobx-react-lite package.

By using MobX, you can maintain the state of your application in a more organized and efficient way, resulting in better performance and maintainability.