Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Sync the UI with the app state using MobX observable and observer in React

    15 - 16
    2 - 5

    Applications are driven by state. Many things, like the user interface, should always be consistent with that state. MobX is a general purpose FRP library that provides the means to derive, for example, a React based user interface automatically from the state and keep it synchronized.

    The net result of this approach is that writing applications becomes really straight-forward and boilerplate free.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Here's a very simple counter application built using React. The counter application has one piece of state, the count. The count is used in the rendering. The basic question that MobX tries to answer is, "How can we keep this count consistent with the rendering?"

    To synchronize the rendering of the state, we are going to use two functions from MobX. The first one is observable. We use observable to decorate our state to count attributes. We say, "MobX, please track this value, so that you can update observers whenever needed."

    Next, we mark our component with the observer decorator from the MobX React package. It simply tells MobX, "This component's rendering can be derived from the relevant observables. Do so whenever needed."

    The next thing we need to do is to implement our built-in handler. That is a really straightforward task, because we trust MobX to keep components rendering consistent with the state. Our actions now consist of simple mutations to our observable state.

    That is enough to have our component react to them. Even more important is that we now have established a separation of concern between the observable state and the component that reacts with. Again, exploit the separation of concern by moving all the state out of the components into a separate store or state. We move the logic along with it.

    We adjust our counter component, and we pass in the store explicitly as property. We refer to this store in our rendering, and in our action handlers. As you will see, the counter now still works as we would expect.

    Just for fun, we can prove this reactive relationship between observer and observable by even removing the props, and accessing the state directly from the closure. Still, the component will react to it as it should.

    That concludes this intro to MobX. There is state marked with observable, and there are components which automatically derive from it, marked by observer.