Autoplay

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

    Michel WeststrateMichel Weststrate

    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.

    reactReact
    15 - 16
    mobxMobX
    2 - 5
    Code

    Code

    Become a Member to view code

    You must be a 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
    Transcript

    Transcript

    00:00 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?"

    00:18 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."

    00:41 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."

    00:57 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.

    01:12 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.

    01:44 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.

    02:04 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.

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

    Discuss

    Discuss