Swizec Teller - a geek with a hatswizec.com

    Livecoding #25: Adding MobX to a vanilla React project

    This is a Livecoding Recap – an almost-weekly post about interesting things discovered while livecoding ?. Always under 500 words and with pictures. You can follow my channel, here. New content almost every Sunday at 2pm PDT. There’s live chat, come say hai ?

    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, following the unidirectional dataflow paradigm: 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 step 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.

    class App extends Component {
    store = new Store();
    render() {
    // change all this.state to this.store

    And you're done. Mostly.

    From this point onward, you should use this.store instead of this.state, and you can ignore this.setState in favor of 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.


    Tomorrow, we'll talk about refactoring that into actions so your business logic becomes an easy-to-understand state machine.

    Did you enjoy this article?

    Published on October 31st, 2016 in Front End, Livecoding, react, Technical

    Learned something new?
    Want to become an expert?

    Here's how it works 👇

    Leave your email and I'll send you thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

    Join Swizec's Newsletter

    And get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career. Real lessons from building production software. No bullshit.

    "Man, love your simple writing! Yours is the only newsletter I open and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

    ~ Ashish Kumar

    Join over 14,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

    Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

    Ready to Stop copy pasting D3 examples and create data visualizations of your own?  Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

    Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

    Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

    Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

    By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️

    Created by Swizec with ❤️