28,14 €
Apply functional Reactive programming for simple and scalable state management with MobX
Key Features
Book Description
MobX is a simple and highly scalable state management library in JavaScript. Its abstractions can help you manage state in small to extremely large applications. However, if you are just starting out, it is essential to have a guide that can help you take the first steps. This book aims to be that guide that will equip you with the skills needed to use MobX and effectively handle the state management aspects of your application.
You will first learn about observables, actions, and reactions: the core concepts of MobX. To see how MobX really shines and simplifies state management, you'll work through some real-world use cases. Building on these core concepts and use cases, you will learn about advanced MobX, its APIs, and libraries that extend MobX.
By the end of this book, you will not only have a solid conceptual understanding of MobX, but also practical experience. You will gain the confidence to tackle many of the common state management problems in your own projects.
What you will learn
Who this book is for
This book is for web developers who want to implement easy and scalable state management for their apps. Knowledge of HTML, CSS, and JavaScript is assumed
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 269
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author(s), nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Kunal ChaudariAcquisition Editor: Reshma RamanContent Development Editor: Aditi GourTechnical Editor: Sushmeeta JenaCopy Editor:Safis EditingProject Coordinator: Hardik BhindeProofreader: Safis EditingIndexer: Aishwarya GangawaneGraphics: Jason MonteiroProduction Coordinator: Arvindkumar Gupta
First published: July 2018
Production reference: 1230718
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78934-483-7
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
I started my journey on Reactive Programming several years ago, when Reactive Programming on frontend wasn't "a thing".
At the beginning, there weren't many references or books available to apply this paradigm on frontend applications; therefore, I had to spent a lot of time extracting the key concepts of Reactive Programming from books on Java or Clojure, university white papers, and blog posts.
In the past two years though, slowly but steadily, the community started developing many frameworks and libraries that shape the frontend Reactive ecosystem we know nowadays.
Reactive Programming is getting a lot of traction. Companies such as Netflix, Microsoft, IBM, and many others are using this paradigm, leveraging the strong decoupling provided out of the box by this paradigm and the unidirectional data flow used in many Reactive state management systems.
From the developers, community, we had a strong push on sharing great reactive implementations, such as Rx.JS, Cycle.js, VueX, SAM patterns, Angular with NGRX, and many others.
There is one though that is standing out from the crowd, created by a bunch of smart developers; it is called MobX.
MobX is the perfect companion for starting your journey on Reactive Programming. It is easy to learn, applies reactivity with a few lines of code, and it could be used without deeply knowing this paradigm. It can also be used for digging into the reactive programming roots.
MobX ecosystem provides the flexibility of structuring small projects, such as a Proof of Concept (PoC), or large projects managed by several teams, thanks to MobX State Tree (MST).
I had the opportunity to work on both MobX and MST: I created some simple PoCs for validating my theories, and also architected a micro-frontend system with tens of developers working with MST.
I saw how well thought out and designed this system was and how fast it was, picking it up from scratch, by other developers.
As you will discover in these pages, MobX will provide you with the flexibility smartness behind architectural and design decisions that you were looking for. It is the perfect companion for any experienced person or a newcomer to the reactive programming movement.
Enjoy your journey into MobX and MST, I'm sure you won't regret it!
Luca Mezzalira
Author, Speaker, Chief Architect at DAZN, Google Developer Expert and manager of the London JavaScript community
Pavan Podila has been building frontend applications since 2001 and has used a variety of tools, technologies, and platforms, from Java Swing, WPF with .Net/C#, Cocoa on macOS and iOS, to the web platform with frameworks such as React and Angular. He has been working with React since 2013 and MobX since 2016. He is a colead of the Interactive Practice at Publicis.Sapient, where he builds large financial applications for web and mobile platforms.
He has been a Microsoft MVP for client application development (2008-2011), and a published author of WPF Control Development Unleashed (Addison-Wesley). He created QuickLens, a Mac app for UI designers/developers, and authored several articles and video courses on Tuts+.
Pavan is a Google Developer Expert (GDE) for web technologies and currently authors courses on The UI Dev. He is a regular speaker at meetups, conferences, and workshops. When time permits, you can find him sketching on iPad or playing ping-pong.
Michel Weststrate (Msc) is tech lead and open source evangelist at Mendix. He has been active as both a frontend and backend developer in different stacks. An occasional speaker at software conferences, he has authored video courses on egghead.
Intrigued by several (transparent) reactive programming libraries, he researched and worked on making the ReactJS framework more reactive while addressing predictability and maintainability constraints in other solutions. This led to mobservable (nowadays MobX), which was quickly adopted at Mendix.
He's very active in the open source software community, and he authored MobX, Immer, and several small libraries, and coauthored MST.
Naresh Bhatia is a passionate technologist and architect who has spent his career helping developers write better software. He leads the Visualization Practice at Publicis.Sapient, which builds interfaces and data visualizations for financial institutions and energy firms. Before joining Sapient, he founded a startup that built domain modeling, code generation, and reverse engineering tools. Naresh graduated with a master's degree in electrical engineering from Illinois Institute of Technology.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
MobX Quick Start Guide
Dedication
Packt Upsell
Why subscribe?
PacktPub.com
Foreword
Contributors
About the authors
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Code in Action
Conventions used
Get in touch
Reviews
Introduction to State Management
The client state
Handling changes in state
The side effect model
A speed tour of MobX
An observable state
Observing the state changes
It's time to take action
A comparison with Redux
Redux in a nutshell
MobX versus Redux
Summary
Observables, Actions, and Reactions
Technical requirements
Observables
Creating observables
Observable arrays
Observable maps
A note on observability
The computed observable
Better syntax with decorators
Actions
Enforcing the use of actions
Decorating actions
Reactions
autorun()
reaction()
A reactive UI
when()
when() with a promise
Quick recap on reactions
Summary
A React App with MobX
Technical requirements
The book search
Observable state and actions
Managing the async action
The Reactive UI
Getting to the store
The SearchTextField component
The ResultsList component
Summary
Crafting the Observable Tree
Technical requirements
The shape of data
Controlling observability
Using @decorators
Creating shallow observables with @observable.shallow
Creating reference-only observables with @observable.ref
Creating structural observables with @observable.struct
Using the decorate() API
Decorating with observable()
Extending the observability
Derived state with @computed
Structural equality
Modeling the stores
Observable state
Derived state
Actions
Summary
Derivations, Actions, and Reactions
Technical requirements
Derivations (computed properties)
Is it a side effect?
There's more to computed()
Error handling inside computed
Actions
Why an action?
Async actions
Wrapping with runInAction()
flow()
Reactions
Configuring autorun() and reaction()
Options for autorun()
Options for reaction()
When does MobX react?
The rules
Summary
Handling Real-World Use Cases
Technical requirements
Form validation
The interactions
Modeling the observable state
Onto the actions
Completing the triad with reactions
React components
The UserEnrollmentForm component
Other observer components
Page routing
The Cart checkout workflow
Modeling the observable state
A route for a step, a step for a route
The WorkflowStep
 Actions and reactions of the workflow
Loading a step
The HistoryTracker
The React components
The TemplateStepComponent
The ShowCart component
A state-based router
Summary
Special API for Special Cases
Technical requirements
Direct manipulation with the object API
Granular reads and writes
From MobX to JavaScript
Watching the events flow by
Hooking into the observability
Lazy loading the temperature
Gatekeeper of changes
Intercepting the change
observe() the changes
Development utilities
Using spy() to track the reactivity
Tracing a reaction
Visual debugging with mobx-react-devtools
A few other APIs
Querying the reactive system
Probing deeper into the reactive system
Summary
Exploring mobx-utils and mobx-state-tree
Technical requirements
The utility functions of mobx-utils
Visualizing async-operations with fromPromise()
Using lazyObservable() for deferred updates
A generalized lazyObservable() with fromResource()
A view model to manage edits
There is lot more to discover
An opinionated MobX with mobx-state-tree
Models – properties, views, and actions
Defining actions on the model
Creating derived information with views
Fine-tuning primitive types
Composing trees
References and identifiers
Referencing by types.identifier() and types.reference()
Out-of-the-box benefits of declarative models
Immutable snapshots
JSON patches
Middlewares
Further reading
Summary
Mobx Internals
Technical requirements
A layered architecture
The Atom
Reading atoms at runtime
Creating an Atom
The atomic clock example
ObservableValue
ComputedValue
Efficient computation
Derivation
The cycle of derivation
Exception handling
The API layer
Transparent functional reactive programming
It is Transparent...
It is reactive...
It is functional...
Value Oriented Programming
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Reactive programming has captured the imagination of programmers for decades. Once the gang of four standardized the observer design pattern, the term has become part of the standard vocabulary of every programmer:
Nonetheless, there is a wide variety of technologies, libraries, and frameworks implementing the observer pattern. Yet, MobX is unique in the way it applies this pattern to state-management. It has a very friendly syntax, a small core API that makes it easy to learn as a beginner, and it can be applied in any JavaScript project. Moreover, the library has proven scalable, not just at Mendix where the project was first applied, but also in famous projects, such as Microsoft Outlook, Battlefield 1 by DICE, Jenkins, Coinbase, and many, many more.
This book will not just guide you through the basics; it will also immerse you in the philosophy of MobX: Anything that can be derived from the application state, should be derived. Automatically.
MobX is not the first of its kind, but it is standing on the shoulders of giants and has pushed the boundaries of what is possible with the transparent reactive programming paradigm. For example, it is, as far as the authors know, the first major library that combines reactivity with synchronous transactions and the first to explicitly distinguish the concept of derived-values and automatic side effects (reactions).
Unlike many learning materials, this book guides you through the inner workings of MobX and its many extension points. This book will hopefully leave a lasting impression that an essentially simple (and very readable!) paradigm can be used to accomplish tasks that are very challenging, not just in terms of domain complexity, but also in terms of performance.
State management plays a crucial role in any application where state is relevant across different places in the code base. This is either because there are multiple consumers or multiple producers of data. In practice, this means that MobX is useful in any application that has a non-trivial amount of data entry or data visualization.
MobX has official bindings for React.js, Preact, and Angular. However, many have used the library in combination with libraries and frameworks such as jQuery, konva.js, Next.js, Vue.js, and even Backbone. When working through the book, you will discover that the concepts required to use a tool like MobX are universally applicable in any environment.
Chapter 1, Introduction to State Management, starts with a conceptual treatment of state-management and its many nuances. It introduces the side-effect model and prepares you with the philosophy needed to understand MobX. Finally, it gives a speed tour of MobX and some of its core building blocks.
Chapter 2, Observables, Actions, and Reactions, takes a deeper look at the core building blocks of MobX. It shows you the various ways of creating observables, using actions to cause mutations on the observables, and, finally, the use of reactions to react to any changes happening on the observables. These three form the core triad of MobX.
Chapter 3, A React App with MobX, combines the knowledge gained so far to power a React App with MobX. It tackles the use case of searching books in an online store. The app is built by first identifying the core observable state, using actions to mutate the state, and using reactions via the observer() utility from mobx-react. The React components are the observers that react to changes in the observable state and automatically render the new state. This chapter will give you an early taste of how simple MobX can be for state management in React apps.
Chapter 4, Crafting the Observable Tree, puts laser focus on designing the observable state with the various options in MobX. We will tackle how to limit the observability in MobX and learn how to create a tight observable state that only observes the necessary and nothing more. In addition to limiting observability, we will also see how to expand the observability with extendObservable(). Finally, we will look into computed properties and look at the use of ES2015 classes to model the observable state.
Chapter 5, Derivations, Actions, and Reactions, goes further into the core building blocks of MobX and explores the API in greater detail. It also touches upon the philosophies governing these building blocks. By the end of this chapter, you will cement your understanding and core intuitions around MobX.
Chapter 6, Handling Real-World Use Cases, is where we apply MobX to two important real-world use cases: form handling and page routing. Both are very visual in nature, but we will argue that they can be dealt with much more easily when represented as observable state, actions, and reactions in MobX. This representation makes the React components (the observers) a natural visual extension of the state. We will also develop our core intuitions around state modelling with MobX.
Chapter 7, Special API for Special Cases, is a survey of APIs that are low level and capable but hide in the shadows of the top-level APIs. such as observable(), action(), computed(), and reaction(). We will explore these low-level APIs and then take a brief tour of the debug utilities available for MobX developers. It is comforting to know that MobX has your back from all angles, even in those rare, odd cases.
Chapter 8, Exploring mobx-utils and mobx-state-tree, gives you a taste of some useful packages that can simplify the everyday use cases encountered in MobX-driven development. As the name suggests, mobx-utils is a utility tool belt containing an assortment of functions. On the other hand is the powerful mobx-state-tree, commonly referred to as MST, that prescribes an approach for scalable MobX applications, baking in patterns that you get for free, once you adopt the MST style of thinking. It is a worthy upgrade to MobX and a must-have for serious users.
Chapter 9, MobX Internals, is where we culminate by peeling off the layers and peeking into the inner workings of MobX. The core abstractions are surprisingly simple and well defined, and they neatly separate the responsibilities. If the term transparent functional reactive programming sounds like a black art, this is the chapter that will unravel the magic and reveal how MobX embraces it. This chapter is also an initiation into the MobX code base and a worthy read for anyone aspiring to be a core contributor to the MobX project.
MobX is typically used in programming environments where long-living, in-memory state plays an important role, most notably web, mobile, and desktop applications. The book requires basic understanding of the JavaScript programming language, and will use modern ES2015 syntax in its examples. Frontend examples are based on the ReactJS framework, so some familiarity with it will be useful, but it's not necessary.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/MobX-Quick-Start-Guide. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: http://www.packtpub.com/sites/default/files/downloads/MobXQuickStartGuide_ColorImages.pdf.
Visit the following link to check out videos of the code being run:http://bit.ly/2NEww85
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
The heart of your React app lives in the client state (data) and is rendered via React components. Managing this state can become tricky as you tackle user interactions (UI), perform async operations, and handle domain logic. In this chapter, we will start with a conceptual model of state management in UI, the role of side effects, and the flow of data.
Then, we will take a quick tour of MobX and introduce its core concepts. These concepts will help in drawing some comparisons with Redux. You will see that MobX turns out to be a more declarative form of Redux!
The topics covered in this chapter are as follows:
What is the client state?
The side effect model
A speed tour of MobX
The UI that you can see and manipulate on screen is the result of painting a visual representation of data. The shape of data hints at the kind of controls you provide for visualizing and manipulating this data. For example, if you have a list of items, you will likely show a List control that has an array of ListItems. Operations may include searching, paginating, filtering, sorting, or grouping the items in the list. The state of these operations is also captured as data and informs the visual representation.
The following diagram shows the direct relationship of an array with a List control:
In short, it is the data that takes on a pivotal role in describing the UI. Handling the structure and managing the changes that can happen to this data is what we commonly refer to as state management. State is just a synonym for the client-data that is rendered on the UI.
As the complexity of the UI increases, more state is accumulated on the client. It gets to a point where state becomes the ultimate source of truth for whatever we see on the screen. This approach to UI development, where we elevate the importance of the client-state, has been one of the biggest shifts in the frontend world. There is an interesting equation that captures this relationship between UI and state:
fn is a transformation function that is applied on the state (the data) that produces a corresponding UI. In fact, a subtle meaning that is hidden here is that, given the same state, fn always produces the same UI.
In the context of React, the preceding equation can be written as follows:
The only difference here is that fn takes two inputs, props and state, which is the prescribed contract of a React component.
However, the preceding equation is only giving half the story of a UI. It's true that the visual representation is derived from the state (through the transformation function, fn), but it does not account for the user operations that occur on the UI. It's like we have completely ignored the user in the equation. After all, the interface is not just used to visually represent data (state), but to also allow the manipulation of that data.
This is where we need to introduce the concept of actions that represent these user operations, which results in a change in state. Actions are the commands that you invoke as a result of various input-events that are fired. These actions cause a change in the state, which is then reflected back on the UI.
We can visualize the triad of State, UI, and Actions in the following figure:
It is worth noting that the UI does not change the state directly, but instead does it via a message-passing system by firing actions. The action encapsulates the parameters that are required to cause the appropriate change in state. The UI is responsible for capturing various kinds of user events (clicks, keyboard presses, touches, voice, and so on) and translating them into one or more actions that are then fired to change the state.
When the State changes, it notifies all of its observers (subscribers) of the change. The UI is also one of the most important subscribers that is notified. When that happens, it re-renders and updates to the new state. This system of data flow from the State into the UI is always uni-directional and has become the cornerstone of state management in modern UI development.
One of the biggest benefits of this approach is that it becomes easy to grasp how the UI is kept in sync with changing data. It also cleanly separates the responsibilities between rendering and data changes. The React framework has really embraced this uni-directional data flow and you will see this adopted and extended in MobX as well.
Now that we understand the roles of UI, state, and actions, we can extend this to build a mental model of how a UI needs to operate. Reflecting back on the triad of Action --> State --> UI, we can make some interesting observations that are not clearly answered. Let's think about how we would handle operations such as the following:
Downloading data from a server
Persisting data back on the server
Running a timer and doing something periodically
Executing some validation logic when some state changes
These are things that don't fit nicely in our data flow triad. Clearly, we are missing something here, right? You might argue that you could put these operations inside the UI itself and fire actions at certain times. However, that would tack on additional responsibilities to the UI, complicating its operation and also making it difficult to test. From a more academic perspective, it would also violate theSingle Responsibility Principle(SRP). SRP states that a class or a module should have only one reason to change. If we start handling additional operations in the UI, it would have more than one reason to change.
So, it seems like we have some opposing forces in action here. We want to retain the purity of the data flow triad, handle ancillary operations such as the ones mentioned in the preceding list, and not add extra responsibilities to the UI. To balance all of these forces, we need to think about the ancillary operations as something external to the data flow triad. We call these side effects.
Side effects are a result of some state-change and are invoked by responding to the notifications coming from the state. Just like the UI, there is a handler, which we can call the side effect handler, that observes (subscribes to) the state change notifications. When a matching state change happens, the corresponding side effect is invoked:
There can be many side effect handlers in the system, and each of them is an observer of the state. When a part of the state they are observing changes, they will invoke the corresponding side effects. Now, these side effects can also cause a change in state by firing additional actions.
As an example, you could fire an action from the UI to download some data. This results in a state change to some flag, which results in notifications being fired to all the observers. A side effect handler that is observing the flag will see the change and trigger a network call to download data. When the download completes, it will fire an action to update the state with the new data.
The fact that side effects can also fire actions to update the state is an important detail that helps in completing the loop around managing state. So, it's not just the UI that can cause state changes, but also external operations (via side effects) that can affect a state change. This is the mental model of side effects, which can be used to develop your UI and manage the state that it renders. The model is quite powerful and scales very well over time. Later in this chapter and also throughout this book, you will see how MobX makes this side effect model a reality and fun to use.
With these concepts in mind, we are now ready to enter the world of MobX.
