SoFunction
Updated on 2025-04-07

react mobx Basic Usage Example Summary

react mobx basic usage

1. Install mobx

  • yarn add mobx
  • yarn add mobx-react-lite

2. Create a mobx folder to manage all the data in the project uniformly

3. Create a unified management in the mobx folder

import React, { useContext } from "react";
import DemoStore from "./DemoStore";
class RootStore {
  constructor() {
     = DemoStore;
    //If there are other files, please follow the above  }
}
const rootStore = new RootStore()
const context = (rootStore)
const useMobStore = () => useContext(context)
export {useMobStore};

IV. Create a file

import { makeAutoObservable, toJS } from 'mobx';
class DemoStoreData{
	number: 1; // data	constructor() {
	   makeAutoObservable(this)
	}
	// Update data (This method can be asynchronous, and you can update data after adjusting the interface inside)	updateNumber = (data) =>{
		 = data;
	}
}
const DemoStore = new DemoStoreData()
export default DemoStore;

V. Use

// The file created by the three steps is importedimport { useMobStore } from "./mobx/"; 
import { observer } from "mobx-react-lite";
const PageList = () => {
	// The demoStore in three steps is deconstructed	const { demoStore } = useMobStore();
	return (
		<div>
			{}
		</div>
	)
}
export default observer(PageList);

6. Attention

If the component wants to use() for performance optimization
In the optimized component, do not have any mobx-related data and methods
Because the old and new values ​​in the memo function can only listen for values ​​passed through redux or components, and the values ​​passed by mobx cannot be listened for.
The method I currently use is to perform the last layer of optimized components through data transfer. (If there is any optimization method, please feel free to comment and inform us, thank you very much!!!)

Use of mobx based on react

It is a lightweight state manager, so it is very simple (single global data uses class) class with get data method

We need to make the data into global data, and this data cannot pollute the global data -- it should be a closure (in ES6 class is a syntax sugar, which itself is a function)

So you should define a class and then export an instance (because the data is globally general, you cannot export the class, you should export the instance -- singleton mode)

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

class Store{
  //In the version, the data type needs to be declared in the constructor  constructor(){
     makeObservable(
    //Specify the target    this,
   //Define the data type in the current mobx class object  {
    list:observable,
    add:action,
    minus:action,
    amount:computed}
)
}
   list=(Array(8),(_,i)=>{
    return {id:'ID-'+i,name:`Huawei mobile phoneMate2${i}`,price:(() * 2000 + 3000), count: 1}
})
//In the class, there is a getter method, which is a data when usedget amount(){
    return ((r,it)=>{
   r +=  * 
   return r
},0)
}
}
add(key,step){
   ('-------- add',key,step)
   = (it =>{
     if( === key)  += step
     return it
})
  ()
}

minus(key,step){
  ('---------minus',key,step)
  =,map(it =>{
  if( === key)  -=step
  return it
})
}
}
export default new Store()

//newis an instance object Storekind ,Store是导出kind

Lightweight State Manager mobx

mobx is a scalable, lightweight state manager (an indicator related to data complexity)

In the project, some data needs to be managed globally (data exists in common -- such as tokens, user information, data is passed on and cacheable)

Use a library or a technique:

First of all, we need to consider business -- array data -- shopping cart array ([{key: unique identifier, name: product name, price: product unit price, count: quantity}]) -- The quantity method can be modified (add/munis needs to pass the reduced quantity every time, and a unique identifier) ​​-- Shopping cart calculates the total price (amount, each data change must be recalculated)

Use library -> Install:cnpm i -S mobx mobx-react(Mobx and their usage methods and method names are very different, and they have almost nothing in common)

Development process: Restore a shopping cart page, everything is a component, and minimize it to an element (because react does not perform component re-rendering optimization - - There are assignment and rendering optimizations)

Tag component + button component => Make a row component => Make a list component => Make a shopping cart page component => Mount to project component => Index render method

Injection: Use on other components

import React from 'react'
import List from './List'
import {inject,observer} from 'mobx-react'
function Cart({cart}){
   return(
  <div>
  <h1>{}</h1>
</div>
)
} 
export default inject('cart')(observer(Cart))
//injectIt's a pure function There is data insidestate , observerIt's the method of observation There are components inside

2. Main technologies are implemented:

Download, install and use

2. Use the class class as a global data instance, and export the instance object in new

.Introduce store data instance object, -- its principle is still the Context principle of react, import {Provider} from 'mobx-react'

b. Use Provider to wrap components and pass values ​​across components <Provider><App/></Provider>

4. Get the data in mobx and use inject method import {inject} from 'mobx-react'

It is a pure function: it will directly specify the property to be injected into the Provider provided. You need to add formal parameters to use the data function List(){return()}

const NewList = inject('cart')(List)   -->Data - -> Component name ===> When using it, add data parameters to the component and use it directly.

export default NewList    

b. Use binding syntax to expand data when issuing data

Version

a. Constructor declares data type

constructor(){
  makeObservable(
 //Point tothis,
{    //Define the data type in the current mobx class object  list:observable,
  add:action,
  minus:action,
  amount:computed
})
}

b. Add listening attributes to page components is to add attributes to data import {cart,observer} from 'react-mobx'

let ObersverComponent = observer(List)
export default inject('cart')(observerCompent)

It is used to observe whether the observable data object in the cart has changed. If it changes, then the page will be re-executed to render the data.

Mobx features: global data modification method monitoring, action transmission parameters and modification, inject data is injected into component usage data, current page rendering initializes data parameters,

Listen to modify the property observer (cart)

This is the end of this article about the usage of react mobx. For more related usage of react mobx, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!