The missing use-store (or use-observable) hook for MobX and MobX-React.
It allows you to subscribe to MobX store without using mobx-react's observer High Order Component.
This hook is highly experimental, although fun, it might be dangerous to use it in production :(
npm install use-mobx-store
.
import React from 'react';
import { UseStoreProvider } from 'use-mobx-store';
import { Button } from './Button';
import logo from './logo.svg';
export const App = () => {
return (
<UseStoreProvider>
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<Button />
</header>
</div>
</UseStoreProvider>
);
};
import { RegisterStore } from 'use-mobx-store';
import { observable } from 'mobx';
@RegisterStore()
export class CountStore {
@observable
pressCount = 0;
increaseCounter = () => {
this.pressCount += 1;
};
}
import { RegisterStore, InjectStore } from 'use-mobx-store';
import { CountStore } from './count-store';
@RegisterStore()
export class ButtonStore {
@InjectStore(CountStore)
private countStore: CountStore;
handlePress = () => {
this.countStore.increaseCounter();
};
}
import React from 'react';
import { CountStore } from './stores/count-store';
import { useStore } from 'use-mobx-store';
import { ButtonStore } from './stores/button-store';
export const Button = () => {
const countStore = useStore(CountStore);
const buttonStore = useStore(ButtonStore);
return <button onClick={countStore.increaseCounter}>I have been pressed {buttonStore.handlePress} times</button>;
};