Optimize Performance in a React App with MobX @computed Properties

Share this video with your friends

Social Share Links

Send Tweet

MobX provides a neat little @computed decorator to exploit the I know when you change nature of observables for performance, fun and profit.

In this lesson we look at an example use case for @computed getters and their performance advantages.

Instructor: [00:01] We kick off with the simple MobX React typescript application. We have Hello Data that contains a simple observable and an action. We have a simple Hello Observer component that uses this data and the render method.

[00:19] We render this component to the application root. When we click the button, an increment of the MobX observable causes the Hello component to re-render with the new count.

[00:30] Now, let's say we want to show additional UI based on whether the button has been clicked at least once or not. We can do it easily with a simple conditional check and showing a div if the condition is met. Now, as we click the button, this new div shows up.

[00:55] Since this condition is derived from the click count member of the data class, we can move it into a nice getter with the semantic name into the data class that will help future maintenance of that class understand the data flow a bit better.

[01:14] As we go and click the button, you can see the application still functions as expected. For these simple getters that can be derived from observables, MobX provides the computed decorator which does not change the observed behavior of an application.

[01:36] If we go ahead and click the button, you can see that it still functions same as before. However, we get a neat optimization for free here. MobX will only re-run this getter if the value of the click count changes. If none of the observables in a computed have changed, the getter simply returns the last value without running its body.

[02:07] To demonstrate this, let's go ahead and add a log to the getter body. Within the render function, we access this getter twice. Now, without the computed annotation, the getter would get called twice.

[02:29] However, as we've annotated it as a MobX computed, when we run the application, you can see that the body of the getter only executes once for each render, even though its value is accessed twice. This is because MobX knows that the observable value used by the getter hasn't changed, and therefore doesn't need to re-run the body to get the new result.

[02:59] This is just another example of MobX taking advantage of the observables to give you the best performing UI application with minimal effort.