Convert Figma logo to code with AI

mobxjs logomobx

Simple, scalable state management.

27,458
1,763
27,458
65

Top Related Projects

227,213

The library for web and native user interfaces.

207,677

This is the repo for Vue 2. For Vue 3, go to https://github.com/vuejs/core

60,792

A JS library for predictable global state management

33,863

Build forms in React, without the tears 😭

30,605

A reactive programming library for JavaScript

27,504

Create the next immutable state by mutating the current one

Quick Overview

MobX is a simple, scalable state management library for JavaScript applications. It makes state management easy by automatically tracking and updating dependencies between state and computations, ensuring that your application's UI stays in sync with the underlying data.

Pros

  • Simple and intuitive API, making it easy to learn and use
  • Efficient updates with minimal boilerplate code
  • Works well with React but can be used with any UI framework
  • Supports both object-oriented and functional programming styles

Cons

  • Can lead to overuse of observables, potentially complicating the codebase
  • Debugging can be challenging due to automatic updates
  • Less suitable for large-scale applications with complex state management needs
  • Smaller community compared to some other state management solutions

Code Examples

  1. Creating and using observables:
import { makeObservable, observable, action } from "mobx";

class TodoStore {
  todos = [];

  constructor() {
    makeObservable(this, {
      todos: observable,
      addTodo: action
    });
  }

  addTodo(task) {
    this.todos.push({ task, completed: false });
  }
}

const store = new TodoStore();
store.addTodo("Buy groceries");
console.log(store.todos); // [{ task: "Buy groceries", completed: false }]
  1. Using computed values:
import { makeObservable, observable, computed } from "mobx";

class TodoStore {
  todos = [];

  constructor() {
    makeObservable(this, {
      todos: observable,
      completedTodos: computed
    });
  }

  get completedTodos() {
    return this.todos.filter(todo => todo.completed);
  }
}

const store = new TodoStore();
store.todos.push({ task: "Buy groceries", completed: true });
store.todos.push({ task: "Clean house", completed: false });
console.log(store.completedTodos.length); // 1
  1. React integration with observer:
import React from "react";
import { observer } from "mobx-react-lite";
import { makeObservable, observable, action } from "mobx";

class CounterStore {
  count = 0;

  constructor() {
    makeObservable(this, {
      count: observable,
      increment: action
    });
  }

  increment() {
    this.count++;
  }
}

const store = new CounterStore();

const Counter = observer(() => (
  <div>
    Count: {store.count}
    <button onClick={() => store.increment()}>Increment</button>
  </div>
));

export default Counter;

Getting Started

To start using MobX in your project:

  1. Install MobX:

    npm install mobx
    
  2. If using React, also install mobx-react-lite:

    npm install mobx-react-lite
    
  3. Create a store with observables and actions:

    import { makeObservable, observable, action } from "mobx";
    
    class Store {
      value = 0;
    
      constructor() {
        makeObservable(this, {
          value: observable,
          increment: action
        });
      }
    
      increment() {
        this.value++;
      }
    }
    
    export const store = new Store();
    
  4. Use the store in your components with the observer HOC:

    import { observer } from "mobx-react-lite";
    import { store } from "./store";
    
    const Component = observer(() => (
      <div>
        Value: {store.value}
        <button onClick={() => store.increment()}>Increment</button>
      </div>
    ));
    

Competitor Comparisons

227,213

The library for web and native user interfaces.

Pros of React

  • Larger ecosystem and community support
  • More mature and battle-tested in production environments
  • Extensive documentation and learning resources

Cons of React

  • Steeper learning curve, especially for beginners
  • Requires additional libraries for state management (e.g., Redux)
  • More boilerplate code for complex applications

Code Comparison

React:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

MobX:

import { makeAutoObservable } from 'mobx';
import { observer } from 'mobx-react-lite';

class Counter {
  count = 0;
  constructor() {
    makeAutoObservable(this);
  }
  increment() {
    this.count++;
  }
}

const CounterView = observer(({ counter }) => (
  <button onClick={() => counter.increment()}>{counter.count}</button>
));

Summary

React is a widely adopted library for building user interfaces, offering a robust ecosystem and extensive community support. However, it may require additional libraries for state management and has a steeper learning curve. MobX, on the other hand, provides a simpler approach to state management with less boilerplate, but has a smaller ecosystem compared to React. The choice between the two depends on project requirements and team preferences.

207,677

This is the repo for Vue 2. For Vue 3, go to https://github.com/vuejs/core

Pros of Vue

  • More comprehensive framework with built-in routing and state management
  • Gentler learning curve, especially for beginners
  • Better performance for large-scale applications

Cons of Vue

  • Less flexible than MobX for state management in non-Vue projects
  • Slightly more opinionated, which may limit customization options
  • Larger bundle size compared to MobX

Code Comparison

Vue:

<template>
  <div>{{ message }}</div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello Vue!'
    }
  }
}
</script>

MobX:

import { makeObservable, observable, action } from "mobx"

class Store {
  message = "Hello MobX!"

  constructor() {
    makeObservable(this, {
      message: observable,
      updateMessage: action
    })
  }

  updateMessage(newMessage) {
    this.message = newMessage
  }
}

Vue provides a more structured approach with its template and script sections, while MobX offers a more flexible, class-based structure for managing state. Vue's reactivity is built-in, whereas MobX requires explicit decoration of observable properties and actions.

60,792

A JS library for predictable global state management

Pros of Redux

  • Predictable state management with a single source of truth
  • Time-travel debugging and easy state reproduction
  • Large ecosystem with middleware and developer tools

Cons of Redux

  • Steep learning curve and boilerplate code
  • Verbose syntax for simple state changes
  • Performance concerns with large state trees

Code Comparison

Redux:

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    default:
      return state;
  }
};

MobX:

class Store {
  @observable count = 0;
  @action increment() {
    this.count++;
  }
}

Redux requires more boilerplate code and explicit action definitions, while MobX allows for more concise and intuitive state updates. Redux enforces immutability and provides a clear flow of data, whereas MobX uses observables and reactions for automatic state tracking and updates.

Both libraries have their strengths and use cases. Redux is often preferred for large-scale applications with complex state management needs, while MobX is favored for its simplicity and ease of use in smaller to medium-sized projects.

33,863

Build forms in React, without the tears 😭

Pros of Formik

  • Specialized for form handling, offering a more focused and streamlined API
  • Integrates well with Yup for schema validation
  • Lighter weight and easier to learn for form-specific tasks

Cons of Formik

  • Limited to form management, unlike MobX's broader state management capabilities
  • May require additional libraries for complex state management scenarios
  • Less flexibility for handling non-form related state

Code Comparison

Formik:

<Formik
  initialValues={{ email: '', password: '' }}
  onSubmit={(values) => console.log(values)}
>
  {({ handleSubmit, handleChange }) => (
    <form onSubmit={handleSubmit}>
      <input name="email" onChange={handleChange} />
      <input name="password" type="password" onChange={handleChange} />
      <button type="submit">Submit</button>
    </form>
  )}
</Formik>

MobX:

class FormStore {
  @observable email = '';
  @observable password = '';

  @action setEmail(value) { this.email = value; }
  @action setPassword(value) { this.password = value; }
}

const store = new FormStore();

const Form = observer(() => (
  <form onSubmit={() => console.log(store)}>
    <input value={store.email} onChange={(e) => store.setEmail(e.target.value)} />
    <input value={store.password} type="password" onChange={(e) => store.setPassword(e.target.value)} />
    <button type="submit">Submit</button>
  </form>
));
30,605

A reactive programming library for JavaScript

Pros of RxJS

  • More powerful and flexible for complex asynchronous operations
  • Better suited for handling multiple data streams and events
  • Extensive set of operators for data manipulation and transformation

Cons of RxJS

  • Steeper learning curve due to its complexity
  • Can be overkill for simpler applications
  • Requires more boilerplate code for basic operations

Code Comparison

MobX example:

import { observable, action } from 'mobx';

class Store {
  @observable count = 0;
  @action increment() {
    this.count++;
  }
}

RxJS example:

import { BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';

const count$ = new BehaviorSubject(0);
const increment$ = count$.pipe(map(count => count + 1));
increment$.subscribe(count => console.log(count));

Summary

RxJS is more powerful for complex asynchronous operations and handling multiple data streams, but it comes with a steeper learning curve and more boilerplate code. MobX, on the other hand, is simpler to use and requires less code for basic state management, making it more suitable for smaller applications or those with simpler state requirements. The choice between the two depends on the specific needs of your project and the complexity of your application's state management requirements.

27,504

Create the next immutable state by mutating the current one

Pros of Immer

  • Simpler learning curve and API, focusing on immutability
  • Works well with existing Redux setups
  • Allows writing mutable code that produces immutable results

Cons of Immer

  • Less powerful for complex state management scenarios
  • May introduce performance overhead for large state trees
  • Limited to plain JavaScript objects and arrays

Code Comparison

MobX:

import { makeAutoObservable } from "mobx";

class Store {
  todos = [];
  constructor() {
    makeAutoObservable(this);
  }
  addTodo(text) {
    this.todos.push({ text, completed: false });
  }
}

Immer:

import produce from "immer";

const initialState = { todos: [] };
const addTodo = (state, text) =>
  produce(state, draft => {
    draft.todos.push({ text, completed: false });
  });

MobX offers a more comprehensive state management solution with automatic tracking and updates, while Immer focuses on providing an easy way to work with immutable state. MobX is better suited for complex applications with intricate state relationships, whereas Immer shines in simpler scenarios or when integrating with existing Redux setups. The choice between the two depends on the specific needs of your project and your preferred state management approach.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

logo

MobX

Simple, scalable state management.

npm version OpenCollective OpenCollective Discuss on Github Coverage Status View changelog


Documentation

Documentation can be found at mobx.js.org.


Sponsors

MobX is made possible by the generosity of the sponsors below, and many other individual backers. Sponsoring directly impacts the longevity of this project.

🥇🥇 Platinum sponsors ($5000+ total contribution): 🥇🥇


Guilded Canva Parallax

🥇 Gold sponsors ($2500+ total contribution):


One Beyond Frontend Masters Auction Frontier CodeFirst Modulz Coinbase Curology Mendix Facebook Open Source Casino Sites Bugsnag

🥈 Silver sponsors ($500+ total contributions):

mantro GmbH Extremely Heavy Algolia Space307 Blokt UPPER DAZN talentplot EaseUS Route Planner and Route Optimizer

Introduction

Anything that can be derived from the application state, should be. Automatically.

MobX is a signal based, battle-tested library that makes state management simple and scalable by transparently applying functional reactive programming. The philosophy behind MobX is simple:

😙

Straightforward

Write minimalistic, boilerplate-free code that captures your intent. Trying to update a record field? Simply use a normal JavaScript assignment — the reactivity system will detect all your changes and propagate them out to where they are being used. No special tools are required when updating data in an asynchronous process.

🚅

Effortless optimal rendering

All changes to and uses of your data are tracked at runtime, building a dependency tree that captures all relations between state and output. This guarantees that computations that depend on your state, like React components, run only when strictly needed. There is no need to manually optimize components with error-prone and sub-optimal techniques like memoization and selectors.

🤹🏻‍♂️

Architectural freedom

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.


A quick example

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-lite"

// Model the application state.
function createTimer() {
    return makeAutoObservable({
        secondsPassed: 0,
        increase() {
            this.secondsPassed += 1
        },
        reset() {
            this.secondsPassed = 0
        }
    })
}

const myTimer = createTimer()

// Build a "user interface" that uses the observable state.
const TimerView = observer(({ timer }) => (
    <button onClick={() => timer.reset()}>Seconds passed: {timer.secondsPassed}</button>
))

ReactDOM.render(<TimerView timer={myTimer} />, document.body)

// Update the 'Seconds passed: X' text every second.
setInterval(() => {
    myTimer.increase()
}, 1000)

The observer wrapper around the TimerView React component will automatically detect that rendering depends on the timer.secondsPassed observable, even though this relationship is not explicitly defined. The reactivity system will take care of re-rendering the component when precisely that field is updated in the future.

Every event (onClick / setInterval) invokes an action (myTimer.increase / myTimer.reset) that updates observable state (myTimer.secondsPassed). Changes in the observable state are propagated precisely to all computations and side effects (TimerView) that depend on the changes being made.

MobX unidirectional flow

This conceptual picture can be applied to the above example, or any other application using MobX.

Getting started

To learn about the core concepts of MobX using a larger example, check out The gist of MobX page, or take the 10 minute interactive introduction to MobX and React. The philosophy and benefits of the mental model provided by MobX are also described in great detail in the blog posts UI as an afterthought and How to decouple state and UI (a.k.a. you don’t need componentWillMount).

Further resources

The MobX book

The MobX Quick Start Guide ($24.99) by Pavan Podila and Michel Weststrate is available as an ebook, paperback, and on the O'Reilly platform (see preview).

Videos

Credits

MobX is inspired by reactive programming principles, which are for example used in spreadsheets. It is inspired by model–view–viewmodel frameworks like MeteorJS's Tracker, Knockout and Vue.js, but MobX brings transparent functional reactive programming (TFRP, a concept which is further explained in the MobX book) to the next level and provides a standalone implementation. It implements TFRP in a glitch-free, synchronous, predictable and efficient manner.

A ton of credit goes to Mendix, for providing the flexibility and support to maintain MobX and the chance to prove the philosophy of MobX in a real, complex, performance critical applications.

NPM DownloadsLast 30 Days