Skip to content

Instantly share code, notes, and snippets.

@designervoid
Last active October 7, 2022 10:47
Show Gist options
  • Save designervoid/71dc224ecb1782ed11cf8d2050059cf3 to your computer and use it in GitHub Desktop.
Save designervoid/71dc224ecb1782ed11cf8d2050059cf3 to your computer and use it in GitHub Desktop.
Default MobX pattern in React SPA
// 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment