33
loading...
This website collects cookies to deliver better user experience
MobX is a state management "engine", and MobX-State-Tree gives it structure and common tools you need for your app.
useStore
hook to use MST in functional components in a React project./// src/stores/rootStore.ts
import { types } from 'mobx-state-tree';
export const rootStore = types
.model({})
.create({});
types
. This allows us to create a "model", which will hold our data, as well as computed data, and actions to update our data./// src/stores/rootStore.ts
// Add `Instance` to our import from MST
import { type, Instance } from 'mobx-state-tree';
const RootStoreContext = createContext<null | Instance<typeof rootStore>>(null);
export const StoreProvider = RootStoreContext.Provider;
/// src/app.tsx
import { StoreProvider, rootStore } from './stores/rootStore';
export default function App(){
return (
<StoreProvider value={rootStore}>
{ /** rest of your app here */ }
</StoreProvider>
);
}
StoreProvider
and pass as its value, our rootStore
from above./// src/stores/rootStore.ts
export function useStore(){
const store = React.useContext(RootStoreContext);
if(store === null){
throw new Error('Store cannot be null, please add a context provider');
}
return store;
}
rootStore
so we can utilize this./// src/stores/userStore.ts
import { types } from 'mobx-state-tree';
// example store, replace this with your actual stores
export const UserStore = types
.model('UserStore')
.props({
id: types.identifier,
name: types.string,
})
.actions((self) => ({
setName: (name: string) => {
self.name = name;
}
}));
export const UserStoreInitialState = {
id: '',
name: '',
}
/// src/stores/rootStore.ts
import { UserStore, UserStoreInitialState } from './userStore';
export const rootStore = types
.model({
userStore: UserStore,
})
.create({
userStore: UserStoreInitialState,
});
/// src/components/user.ts
import { useStore } from '../stores/rootStore';
export function User(){
const { userStore } = useStore();
return (
<div>
<h1>{userStore.name}</h1>
<button onPress={() => {
userStore.setName('Colby');
})>Update Name</button>
</div>
);
}
mobx-react-lite
package./// src/components/user.ts
import { useStore } from '../stores/rootStore';
import { observer } from 'mobx-react-lite';
export function User observer((){
const { userStore } = useStore();
return (
<div>
<h1>{userStore.name}</h1>
<button onPress={() => {
userStore.setName('Colby');
})>Update Name</button>
</div>
);
});