Using MobX to Isolate a React Component State

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 4 years ago

React is great for diffing between Virtual-DOM and rendering it to the dom. It also offers a naïve solution for diffing state in terms of setState. However it is slightly verbose and not easy to scale. MobX offers a very simple and effective solution to manage state in React components.

Instructor: [00:01] Let's kick off with a simple React TypeScript application.

[00:04] We have a hello component that maintains a local clicked count state. We initialize the state in the constructor. We have a function that increments this using React's setState.

[00:27] Finally, we render a button that increments this count onClick and shows the current click count as its content. We go ahead and render this component into the root of our page.

[00:49] As we go ahead and click the button, the clicked count is incremented and the UI updates accordingly. Using MobX in a React application is super easy. All we need to do is install MobX and MobX React. Since MobX is written in TypeScript, there is no additional setup or type definitions required.

[01:13] The MobX module provides decorators, observable, to mark the property as observable, and action, to carry out mutations in a transactional manner.

[01:26] MobX React provides a decorator, observer, that can wrap a React component to make it reactive to observable's changes. These three, simple decorators are pretty much all you need to be highly productive with MobX.

[01:45] Using MobX, we can isolate the state management for the hello component into a simple hello data class. It contains a simple clicked count observable property, and an increment action that increments this clicked count property using easy-to-understand-and-maintain JavaScript.

[02:08] To use this data class in a React component, we simply decorate the component as an observer. Since we are no longer using React's state, we remove its generic annotation.

[02:22] We simply initialize the data whenever the component is initiated, and then, use this data member in a render function to interact with the state. If you run the demo, you can see that it works same as before.

[02:46] Moving this data management out of the React component means it is completely independent of React. All the data management becomes simple JavaScript that can be tested and reasoned about in isolation, independent of its DOM representation.

[03:02] Using MobX effectively turns React into a simple and effective data to DOM transform.

Basarat Ali Syed
Basarat Ali Syedinstructor
~ 5 years ago

Code at 🌹

~ 3 years ago

Where is typescript? There is no typescript here

Basarat Ali Syed
Basarat Ali Syedinstructor
~ 3 years ago

Indeed TypeScript is very transparent (as it should be) : 🌹