When using ES6 classes with MobX for React development, the observer function is a key feature that transforms React components into reactive ones, enabling them to observe state changes in MobX and re-render when the state updates. Here's how to do it specifically:
Step 1: Install mobx and mobx-react
First, ensure that your project has installed mobx and mobx-react. If not, you can install them using npm or yarn:
bashnpm install mobx mobx-react # or yarn add mobx mobx-react
Step 2: Create a MobX Store
Create a MobX store to manage your application state. For example, we create a simple counter store:
javascriptimport { makeAutoObservable } from "mobx"; class CounterStore { count = 0; constructor() { makeAutoObservable(this); } increment() { this.count++; } decrement() { this.count--; } } const counterStore = new CounterStore(); export default counterStore;
Step 3: Create a React Component Using ES6 Classes
Create a React component and wrap it with the observer function from mobx-react:
javascriptimport React from 'react'; import { observer } from 'mobx-react'; import counterStore from './CounterStore'; @observer // Apply observer using the decorator class Counter extends React.Component { render() { return ( <div> <h1>Count: {counterStore.count}</h1> <button onClick={() => counterStore.increment()}>Increment</button> <button onClick={() => counterStore.decrement()}>Decrement</button> </div> ); } } export default Counter;
Note:
- Using
observermakes React components reactive, meaning any changes to MobX states accessed by the component will trigger re-rendering. - In the above example, we directly import and use the state from the store, which is suitable for simple or moderately complex applications. For more complex applications, you may need to consider using Context or other state management solutions to pass the store.
By following the above steps, you can connect MobX state to React props via the observer higher-order component, enabling the component to respond to state changes. This is a common pattern for integrating React components with MobX state management.