Integrating MobX with React for Local Component State
Show a basic example of using MobX for local state management within a React component, focusing on the simplicity of MobX for fine-grained reactivity compared to global state management solutions.
import { makeAutoObservable } from 'mobx';
import { observer } from 'mobx-react';
import React from 'react';
Imports necessary MobX and React libraries.
class CounterState {
count = 0;
constructor() {
makeAutoObservable(this);
}
increment() {
this.count++;
}
decrement() {
this.count--;
}
}
Defines a simple MobX store with a counter and methods to increment and decrement it.
const Counter = observer(() => {
const counterState = new CounterState();
return (
<div>
<button onClick={() => counterState.decrement()}>-</button>
<span>{counterState.count}</span>
<button onClick={() => counterState.increment()}>+</button>
</div>
);
});
Defines a React component that uses the MobX store. The 'observer' wrapper enhances the component to react to changes in observable state.
export default Counter;
Exports the counter component as the default export.