We are going global

How to setup Mobx with React in 2021

In one of the previous articles I’ve talked about why you should learn React in 2021 and so I was thinking about what to follow it up with. While coding in React you usually need a good global store. Therefore today I want to talk about the setup of my favorite global state store called Mobx. I have been using Mobx for about 4 years already and I have seen it changed over the years quite a lot. It’s always been a problem to set it up with the decorators and babel config. But recently the Mobx team has improved this process quite a lot and I want to walk you through the process.

Install mob libraries

Firstly we have to install mobx and mobx-react-lite with npm:

npm install --save mobx mobx-react-lite

or yarn:

yarn add mobx mobx-react-lite

Create store

Let’s create a store that holds the currently logged in user. We’ve created a new folder “stores” and added an index.js with the following code:

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;

Now I don’t like using classes, but for Mobx it was pretty much always necessary. Anyways we declared currentUser with name “Jozef” and a setUser function for changing the currently logged in user. Now in the constructor we have to make the current user into an observable and the setUser function into an action. This is just how mobx recongizes what is what, before it was done by the @ decorators, now it’s done with the makeObservable function.

See also  Basic setup of a nodeJS project

Creating React context

We have our store ready, all we need to do now is create react context in App.js. This way the whole app has access to the store.

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;

In our Header component we display the currently logged in user from our store. Import the context and get its contents by using react hook useContext.

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);

When we load the page, we see that indeed Jozef is currently logged in.

If we press the button, the store is updated with a new currently logged in user called “Alfred”.

Conclusion

So Guildsmen, it’s a bit shorter article for today, because as you can see it’s super easy to setup Mobx with React in 2021. The Mobx team has done a tremendous job, go check out their official setup. Hope you’ve learned something new and useful today, see you in the next one. 😉🤘

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *