Instructor: We kick off with the simple application from the previous step. We have Hello data that contains an observable and an action, and then a Hello component that uses this data within its render method. Finally, we render this component to the application route.
We go ahead and start this application and visit it at localhost:8080. As we go ahead and click the button, the data.increment method gets called, causing the Hello component to re-render with the new clicked count.
MobX provide excellent React devtools that allow you to observe the changes that take place in actions along with the reactions that take place because of these changes. We install it from npm. Once installed, we can import it into our example application and then render it to the application route along with the Hello component.
The MobX React devtools show up as a nice panel in the UI of our application. The last button in the panel can be used to log actions and reactions within MobX to the console. If we open up the console and click the button, you can see this take place.
Note that we are making all mutations within an action. By default, you can actually mutate observables outside of actions as well. MobX is smart enough to notice this fact and run any reactions that need to take place, for example, re-rendering the component.
However, it is highly recommended that you make all changes within actions and within the class that actually contains the data that you are changing. It is normally not a big deal, especially with TypeScript, when someone mutates data elsewhere, as you can easily find references reliably and refactor them into action calls.
Note that there is actually an option with MobX to configure it to only allow mutations within actions.
We import the configure method from MobX and ask it to enforce actions for all mutations. If any mutation occurs outside of an action, MobX would now throw an error. This is not an option we normally set within projects, as the guidance of mutating data only within action methods is quite easy to follow.
One more thing to note is that MobX only re-renders any components that actually need to re-render to do some observable change. If we log out whenever we render the component, you can see that it renders on first application load and then whenever an observable change occurs in an action.