How to setup Mobx with React in 2021 — JS Guild

Install libraries

npm install --save mobx mobx-react-lite
yarn add mobx mobx-react-lite

Create store

import { action, makeObservable, observable } from "mobx";class Store {
currentUser = {
name: "Jozef",
};
setUser(user) {
this.currentUser = user;
}
constructor() {
makeObservable(this, {
currentUser: observable,
setUser: action,
});
}
}
export default Store;

Creating React context

import Store from "./stores";
import { createContext } from "react";
import Header from "./components/Header";
export const StoreContext = createContext({});function App() {
return (
<StoreContext.Provider value={new Store()}>
<Header />
</StoreContext.Provider>
);
}
export default App;
import { observer } from "mobx-react-lite";
import { useContext } from "react";
import { StoreContext } from "../App";
const Header = () => {
const store = useContext(StoreContext);
return (
<div>
<div>current user: {store.currentUser.name}</div>
<button onClick={() => store.setUser({ name: "Alfred" })}>
change user
</button>
</div>
);
};
export default observer(Header);

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store