Structure of a project:
src/
stores/
Counter.ts
components/
CounterComponent.tsx
// src/stores/Counter.ts | |
import { makeAutoObservable } from 'mobx'; | |
type State { | |
counter: number; | |
}; | |
type Mutations { | |
increment(): void; | |
decrement(): void; | |
}; | |
interface ICounter extends State, Mutations {} | |
class Counter implements ICounter { | |
counter = 0; | |
constructor() { | |
makeAutoObservable(this); | |
}; | |
increment() { | |
this.state.number += 1; | |
}; | |
decrement() { | |
this.state.number -= 1; | |
}; | |
}; | |
export const instanceCounter = new Counter(); |
// src/components/CounterComponent.tsx | |
import { FC } from 'react'; | |
import { instanceCounter } from 'src/stores/Counter'; | |
import { observer } from 'mobx-react' | |
export const CounterComponent: FC = observer(() => { | |
return ( | |
<> | |
<span>{instanceCounter.state.number}</span> | |
<button onClick={() => instanceCounter.increment()}>+</button> | |
<button onClick={() => instanceCounter.decrement()}>-</button> | |
</> | |
); | |
}); |
Structure of a project:
src/
stores/
Counter.ts
components/
CounterComponent.tsx