MobX

Nethmee Kumararatne
2 min readJan 19, 2024

--

What is MobX?
MobX is a state management library for JavaScript applications, commonly used with React. In MobX, observables are the core concept that enables reactivity in your application. Observables are objects or values that can be observed, meaning that when they change, observers are automatically notified, and any reactive components or functions are re-executed.
Here’s what can be made observable in MobX:

1.State Variables:

You can make plain JavaScript objects or class instances observable. Any changes to the properties of these objects trigger reactions in components that are observing them.

import { observable } from ‘mobx’;
const user = observable({
name: ‘John’, age: 25,
});

2. Class Instances:
You can make instances of classes observable. This is useful for creating observable models or stores in your application.

import { observable, action } from ‘mobx’;
class UserStore {
@observable users = [];
@action addUser(user) {
this.users.push(user);
}
}
const userStore = new UserStore();

3. Arrays and Maps:
MobX provides observable versions of arrays and maps that automatically track changes. Any modifications to these structures trigger reactions.

import { observable } from ‘mobx’;
const numbers = observable([1, 2, 3]);
const userMap = observable.map({ id: ‘1’, name: ‘John’ });

4. Computed Values:
Computed values are derived values that are automatically kept in sync with the observable values they depend on. They are created using the computed function.

import { observable, computed } from ‘mobx’;
const temperature = observable({ celsius: 22 });
const temperatureInFahrenheit = computed(() => temperature.celsius * 1.8 + 32);

5.Reactions:
Reactions are functions that automatically run when the observed values they depend on change. They can be used for performing side effects.

import { observable, reaction } from ‘mobx’;
const temperature = observable({ celsius: 22 });
const temperatureReaction = reaction(
() => temperature.celsius,
(newTemperature, reaction) => {
console.log(`Temperature changed to ${newTemperature}°C`);
}
);

By making these entities observable, MobX enables a reactive programming style where your application state is automatically kept in sync with your UI and other dependent logic.

--

--