Reader small image

You're reading from  Learn React Hooks

Product typeBook
Published inOct 2019
Reading LevelIntermediate
PublisherPackt
ISBN-139781838641443
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Daniel Bugl
Daniel Bugl
author image
Daniel Bugl

Daniel Bugl is a CEO, Software Architect and Full Stack Developer for his company TouchLay, developing a platform for interactive presentations. He also consults large multinational enterprises on the development and integration of React frontends with various backend systems, including the integration of legacy systems, and helps out with the setup and development of such projects. He has a bachelor's degree in business informatics and a master's degree in data science.
Read more about Daniel Bugl

Right arrow

MobX and Hooks

In the previous chapter, we learned about Redux and how to use Redux in combination with Hooks. We also learned how to migrate existing Redux applications to a Hook-based solution. Furthermore, we learned about the trade-offs of using Reducer Hooks versus Redux, and when to use either one of them.

In this chapter, we are going to learn how to use MobX in combination with Hooks. We are going to start by learning how to handle state with MobX, then move on to using MobX with Hooks. Furthermore, we will learn how to migrate an existing MobX application to Hooks. Finally, we are going to discuss the pros and cons of using MobX. By the end of this chapter, you will fully understand how to write MobX applications using Hooks.

The following topics will be covered in this chapter:

  • Learning what MobX is and how it works
  • Handling state with MobX
  • Using MobX with Hooks
  • Migrating...

Technical requirements

A fairly recent version of Node.js should already be installed (v11.12.0 or higher). The npm package manager for Node.js also needs to be installed.

The code for this chapter can be found in the GitHub repository: https://github.com/PacktPublishing/Learn-React-Hooks/tree/master/Chapter13.

Check out the following video to see the code in action:

http://bit.ly/2Mm9yoC

Please note that it is highly recommended that you write the code on your own. Do not simply run the code examples that have been provided. It is important that you write the code yourself in order to be able to learn and understand it properly. However, if you run into any issues, you can always refer to the code example.

Now, let's get started with the chapter.

What is MobX?

MobX takes a different approach than Redux. Rather than applying restrictions to make state changes predictable, it aims to automatically update anything that is derived from the application state. Rather than dispatching actions, in MobX we can directly modify the state object and MobX will take care of updating anything that uses the state.

The MobX life cycle works as follows:

  1. Events (such as onClick) invoke actions, which are the only things that can modify state:
@action onClick = () => {
this.props.todo.completed = true
}
  1. State is observable, and should not contain redundant or derivable data. State is very flexible—it can contain classes, arrays, references, or it can even be a graph:
@observable todos = [
{ title: 'Learn MobX', completed: false }
]
  1. Computed values are derived from state through a pure function. These will be automatically...

Handling state with MobX

The best way to learn about MobX is by using it in practice and seeing how it works. So, let's start by porting our ToDo application from Chapter 11, Migrating from React Class Components, to MobX. We start by copying the code example from Chapter11/chapter11_2/.

Installing MobX

The first step is to install MobX and MobX React, via npm. Execute the following command:

> npm install --save mobx mobx-react

Now that MobX and MobX React are installed, we can start setting up the store.

Setting up the MobX store

After installing MobX, it is time...

Using MobX with Hooks

In the previous section, we learned how to use MobX with React. As we have seen, to be able to connect our components to the MobX store, we need to wrap them with the inject function, and in some cases, also with the observer function. Instead of using these higher-order components to wrap our components, since the release of v6 of mobx-react, we can also use Hooks to connect our components to the MobX store. We are now going to use MobX with Hooks!

Defining a store Hook

First of all, we have to define a Hook in order to access our own store. As we have learned before, MobX uses React Context to provide, and inject, state into various components. We can get the MobXProviderContext from mobx-react and...

Migrating a MobX application

In the previous section, we learned how to replace MobX higher-order components, such as inject and observer in existing MobX applications with Hooks. Now, we are going to learn how to migrate local state to Hooks in existing MobX applications.

An existing MobX application can be migrated to a Hook-based solution by following three steps:

  • Using a State Hook for simple local state
  • Using the useLocalState Hook for complex local state
  • Keeping global state in separate MobX stores

We have already learned how to use a State Hook in the early chapters of this book. State Hooks make sense for simple state, such as the current state of a checkbox.

We have already learned how to use the useLocalState Hook in this chapter. We can use the Local State Hook for complex local state, such as complex forms where multiple fields interact with each other. Then, we...

The trade-offs of MobX

To wrap up, let's summarize the pros and cons of using MobX in a web application. First, let's start with the positives:

  • It provides a simple way of dealing with state changes
  • Less boilerplate code is required
  • It offers flexibility in how our application code is structured
  • Multiple global and local stores can be used
  • It makes the App component much simpler (it offloads state management and actions to MobX)

MobX is perfect for small—and large projects—that deal with complex state changes, and state that is used across many components.

However, there are also downsides to using MobX:

  • State changes could happen anywhere, not just in a single store
  • Its flexibility means that it is possible to structure the project in a bad way, which could cause errors or bugs
  • MobX requires a wrapper component (Provider) in order to connect the app...

Summary

In this chapter, we first learned what MobX is, which elements it consists of, and how they work together. Then, we learned how to use MobX for state management in practice. We also learned how to connect a MobX store to React components, by using the inject and observer higher-order components. Next, we replaced the higher-order components with Hooks, which made our code much more clean and concise. We also learned how to use a Local Store Hook to deal with complex local state in MobX. Finally, we learned how to migrate an existing MobX application to Hooks, and we recapped what the trade-offs of using MobX are.

This chapter marks the end of this book. In this book, we started out with a motivation to use Hooks. We learned that there are common problems in React apps that cannot be easily solved without Hooks. Then, we created our first component using Hooks and compared...

Questions

In order to recap what we have learned in this chapter, try to answer the following questions:

  1. Which elements form the MobX life cycle?
  2. Which decorators does MobX provide?
  3. How can we connect components to MobX?
  4. Which Hooks does MobX provide?
  5. How can we access the MobX store using Hooks?
  6. Can we store local state using MobX?
  7. How should we go about migrating an existing MobX application to Hooks?
  8. What are the advantages of using MobX?
  9. What are the disadvantages of using MobX?
  10. When should MobX not be used?

Further reading

If you are interested in more information about the concepts that we have learned in this chapter, take a look at the following reading material:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn React Hooks
Published in: Oct 2019Publisher: PacktISBN-13: 9781838641443
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Daniel Bugl

Daniel Bugl is a CEO, Software Architect and Full Stack Developer for his company TouchLay, developing a platform for interactive presentations. He also consults large multinational enterprises on the development and integration of React frontends with various backend systems, including the integration of legacy systems, and helps out with the setup and development of such projects. He has a bachelor's degree in business informatics and a master's degree in data science.
Read more about Daniel Bugl