DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Coding
  3. JavaScript
  4. Adding MobX to a Vanilla React Project

Adding MobX to a Vanilla React Project

Follow along to learn how to implement MobX or Redux into your vanilla React project to handle the state management of your web application.

Swizec Teller user avatar by
Swizec Teller
·
May. 08, 17 · Tutorial
Like (1)
Save
Tweet
Share
4.30K Views

Join the DZone community and get the full member experience.

Join For Free

Well, this is embarrassing… there's supposed to be an embedded video right here but, I didn't make one.

After an hour of coding and talking and streaming and explaining all the things I was doing and struggling with OBS eating 300% CPU, leaving one core to almost keep up with Emacs and Chrome and Npm and JavaScript, someone said, "Errr… chatting with you is great but… uhm… no video today?"

?

No wonder the view count wasn't rising and everyone was bouncing! I had done 10 seconds of streaming, then I went blank!

But I think I came up with a generalized, albeit not fleshed out, approach to taking a vanilla React project and adding MobX or Redux for state management. You should think of the code samples in this article as pseudocode.

Let's say you've been a good programmer, and you’ve followed a faux flux approach even without a state handling library. React is good at encouraging that practice. If you didn't, you're going to have problems refactoring. If you followed it loosely like I did, you're going to have problems, but not quite as many.

You have a main component that is the source of truth. Child components have a bit of their own state, and they use callback chains to propagate changes back up the tree.

In theory, if we follow the unidirectional data flow paradigm, then: data/state flows down the tree, changes flow up the tree.

This is superb for example projects and small hierarchies, but it gets real messy real fast. You lose a lot of flexibility, and passing all those callbacks around gets old fast.

Oh, you want to make a global state change from a button deep down in this 10-step hierarchy? Better make all those components aware of what the tiny button is doing! Don't even think about moving it somewhere else.

That's where Redux or MobX comes in.

First, you look at your App component's state. Let's say it has 5 important parts:

class App extends Component {
    state = {
        rawData: [],
        filteredData: [],
        filteringBy: null,
        filter: () => true
        someRandomBool: false
    };
}

You can deduce your entire component tree from the value of those 5 properties. If that's not true, then your refactor will require more steps, and most of them will hurt.

Your next step is to create a Redux or MobX store. I'm going to show you MobX because I've been enjoying it a lot lately.

Looking at that state, you can guess that rawData, filteringBy, filter, and someRandomBool are the state properties. filteredData can be computed. It smells like filter might be computable as well, but it's on the fence.

In a MobX store, that looks like this:

class Store {
    @observable rawData = [];
    @observable filteringBy = null;
    @observable filter = () => true;
    @observalbe someRandomBool = false;

    @computed filteredData() {
        return this.rawData.filter(this.filter);
    }
}

@observable is a decorator that makes a variable observable. That's MobX lingo for, "I want stuff to happen when this changes." @computed is a decorator that makes the return value of a method observable and adds memoization.

So no matter how often you hit that function, it only executes when its result might change. Otherwise, it's as fast as a static value.

That's why we used to put computable stuff in this.state. To make things faster. I like this new approach because it tells anyone who cares what's a base state of the system and what's deducible.

After that, you go back to your App, replace state with a store, and make App an observer.

@observer
class App extends Component {
    store = new Store()

    render() {
        // change all this.state to this.store
    }
}

And you're done. Mostly.

From this point on, you should use this.store instead of this.state, and you can ignore this.setState in favor of the good old this.store.someRandomBool = true. MobX's engine will trigger a re-render on any component that is an @observer and touches that value.

Neat!

React (JavaScript library)

Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Mission-Critical Cloud Modernization: Managing Coexistence With One-Way Data Sync
  • Strategies for Kubernetes Cluster Administrators: Understanding Pod Scheduling
  • Choosing the Right Framework for Your Project
  • High-Performance Analytics for the Data Lakehouse

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: