mobx-react-lite usage (works both in React Web and React Native)
install packages
yarn add mobx mobx-react-lite
in ./tsconfig.json
- set compilerOptions.experimentalDecorators = true
- sometimes you need to close project and reopenit, otherwise, it might keep waring: Set the 'experimentalDecorators' option in your 'tsconfig' or 'jsconfig' to remove this warning.ts(1219)
create file src/stores/CounterStore.ts
import { action, makeObservable, observable } from "mobx"; export class CounterStore { constructor() { makeObservable(this) } @observable value: number = 0; @action increment() { this.value += 1; } @action decrement() { this.value -= 1; } }
create file src/stores/index.ts
import React from "react"; import { CounterStore } from "./CounterStore" export const stores = Object.freeze({ counterStore: new CounterStore() }) export const storesContext = React.createContext(stores); export const StoresProvider = storesContext.Provider;
create file src/stores/hooks.ts
import React from 'react' import { stores, storesContext } from "./"; export const useStores = () => React.useContext(storesContext); export const useStore = <T extends keyof typeof stores>( store: T ): typeof stores[T] => React.useContext(storesContext)[store];
in pages
import { useEffect } from "react" import { useStore } from "../../stores/hooks" import { observer } from "mobx-react-lite" const MyPage = observer(() => { const counterStore = useStore('counterStore') useEffect(()=>{ console.log(counterStore?.value) }, [counterStore?.value]) return ( <div> <p><button onClick={()=>counterStore.increment()}>increment</button></p> <p><button onClick={()=>counterStore.decrement()}>decrement</button></p> </div> ) }) export default MyPage
reference: javascript.plainenglish.io/all-you-need-is-mobx-react-lite-47ba0e95e9c8