Product
Introducing License Enforcement in Socket
Ensure open-source compliance with Socketās License Enforcement Beta. Set up your License Policy and secure your software!
MobX is a state management library for JavaScript applications. It enables developers to manage the application state outside of UI frameworks in a reactive way that ensures that the state is consistent and predictable. MobX uses observable data structures and automatically tracks changes, updating the UI when necessary.
Observable State
Create observable state that can be tracked and updated. When the state changes, MobX will automatically propagate changes to any computed values or reactions that depend on the changed state.
import { observable } from 'mobx';
const appState = observable({
count: 0,
increment: function() {
this.count++;
},
decrement: function() {
this.count--;
}
});
Computed Values
Define computed values that will be re-evaluated when any observable data they depend on changes. Computed values are cached and only updated when necessary.
import { computed, makeObservable } from 'mobx';
class TodoList {
todos = [];
get unfinishedTodoCount() {
return this.todos.filter(todo => !todo.finished).length;
}
constructor() {
makeObservable(this, {
todos: observable,
unfinishedTodoCount: computed
});
}
}
Reactions
Reactions are a way to automatically run side effects when observable data changes. The autorun function is one type of reaction that runs immediately and then re-runs every time its dependencies change.
import { observable, autorun } from 'mobx';
const temperature = observable.box(20);
const reaction = autorun(() => {
console.log(`Temperature is: ${temperature.get()}C`);
});
temperature.set(25); // This will trigger the autorun and log the new temperature
Actions
Actions are functions that modify observables. They are the only way to modify state in MobX, and they can be bound to the class instance using the action.bound decorator.
import { observable, action } from 'mobx';
class Store {
@observable count = 0;
@action.bound increment() {
this.count++;
}
@action.bound decrement() {
this.count--;
}
}
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. Unlike MobX, Redux uses a single immutable state tree and pure reducer functions to handle state changes.
Vuex is a state management pattern and library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion. Vuex is similar to Redux and differs from MobX in its strict emphasis on mutation tracking and less focus on reactive programming.
Immer is a tiny package that allows you to work with immutable state in a more convenient way. It uses a copy-on-write mechanism to ensure that the original state is not modified. While Immer is not a state management library like MobX, it can be used with state management libraries to simplify handling immutable data.
Simple, scalable state management
MobX is made possible by the generosity of the sponsors below, and many individual backers. Sponsoring directly impacts the longevity of this project.
š„Gold sponsors ($3000+ total contribution):
š„Silver sponsors ($100+ pm):
š„Bronze sponsors ($500+ total contributions):
Anything that can be derived from the application state, should be derived. Automatically.
MobX is a battle tested library that makes state management simple and scalable by transparently applying functional reactive programming (TFRP). The philosophy behind MobX is simple:
With MobX, you write minimalistic, boilerplate free code that captures your intent: Trying to update a record field? Use good old JavaScript assignment. Updating data in an asynchronous process? No special tools are required. The reactivity system will detect all your changes and propagate them out to where they are being used.
MobX tracks all updates and usages of your data at runtime, building a dependency tree that captures all relations between state and output. This guarantees that computations depending on your state, like React components, run only when strictly needed. With MobX, there is no need to manually optimize components using error-prone and sub-optimal techniques like memoization and selectors.
MobX is unopinionated and allows you to manage your application state outside of any UI framework. This makes your code decoupled, portable, and above all, easily testable.
So what does code that uses MobX look like?
import React from "react"
import ReactDOM from "react-dom"
import { makeAutoObservable } from "mobx"
import { observer } from "mobx-react"
// Model the application state
class Timer {
secondsPassed = 0
constructor() {
makeAutoObservable(this)
}
increaseTimer() {
this.secondsPassed += 1
}
resetTimer() {
this.secondsPassed = 0
}
}
const myTimer = new Timer()
// Build a user interface for this app, that merely uses the state...
const TimerView = observer(({ timer }) => (
<button onClick={() => timer.resetTimer()}>Seconds passed: {timer.secondsPassed}</button>
))
ReactDOM.render(<TimerView timer={myTimer} />, document.body)
// For demo's sake, let's force some updates...
setInterval(() => {
myTimer.increaseTimer()
}, 1000)
The observer
wrapper around the TimerView
React component will automatically detect that rendering
of the component depends on timer.secondsPassed
, even though this relationship is not explicitly defined. MobX's reactivity system will make sure the component gets re-rendered when precisely that field is updated in the future.
Every event (onClick
and setInterval
) invokes an action (increaseTimer
and resetTimer
functions) that updates observable state (secondsPassed
class property).
Changes in the observable state are propagated precisely to all computations and side-effects (TimerView
component) that depend on the changes being made.
You can apply this diagram as a conceptual picture to this simple example or any other application using MobX.
To learn about the core concepts of MobX with a larger example, please read Concepts & Principles or take the 10 minute interactive introduction to MobX and React. The philosophy and benefits of the mental model provided by MobX are described in detail in the blogs UI as an afterthought and How to decouple state and UI (a.k.a. you donāt need componentWillMount).
Guise, #mobx isn't pubsub, or your grandpa's observer pattern. Nay, it is a carefully orchestrated observable dimensional portal fueled by the power cosmic. It doesn't do change detection, it's actually a level 20 psionic with soul knife, slashing your viewmodel into submission.
After using #mobx for lone projects for a few weeks, it feels awesome to introduce it to the team. Time: 1/2, Fun: 2X
Working with #mobx is basically a continuous loop of me going āthis is way too simple, it definitely wonāt workā only to be proven wrong
I have built big apps with MobX already and comparing to the one before that which was using Redux, it is simpler to read and much easier to reason about.
The #mobx is the way I always want things to be! It's really surprising simple and fast! Totally awesome! Don't miss it!
MobX is inspired by reactive programming principles as found in spreadsheets. It is inspired by MVVM frameworks like in MeteorJS tracker, knockout and Vue.js. But MobX brings Transparent Functional Reactive Programming to the next level and provides a stand alone implementation. It implements TFRP in a glitch-free, synchronous, predictable and efficient manner.
A ton of credits for Mendix, for providing the flexibility and support to maintain MobX and the chance to proof the philosophy of MobX in a real, complex, performance critical applications.
FAQs
Simple, scalable state management.
The npm package mobx receives a total of 1,287,328 weekly downloads. As such, mobx popularity was classified as popular.
We found that mobx demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Ā It has 6 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Ensure open-source compliance with Socketās License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.
Product
We're excited to introduce Socket Optimize, a powerful CLI command to secure open source dependencies with tested, optimized package overrides.