MobX Quick Start Guide Supercharge the client state in your React apps with MobX Pavan Podila Michel Weststrate BIRMINGHAM - MUMBAI MobX Quick Start Guide 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 Chaudari Acquisition Editor: Reshma Raman Content Development Editor: Aditi Gour Technical Editor: Sushmeeta Jena Copy Editor: Safis Editing Project Coordinator: Hardik Bhinde Proofreader: Safis Editing Indexer: Aishwarya Gangawane Graphics: Jason Monteiro Production 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 To my loving wife, Sirisha Vardhani, for supporting me all along. – Pavan Podila To my kids, Noa and Veria, who have to regularly pull me back to Earth when my thoughts are wandering off. To my wife, Elise, who always encourages me to pursue new ideas. To God, who shared His ability to be a creator with all of us. – Michel Weststrate mapt.io 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. Why subscribe? 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 PacktPub.com 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. Foreword 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 Contributors About the authors 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. About the reviewer 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. Packt is searching for authors like you 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. Table of Contents Preface 1 Chapter 1: Introduction to State Management 7 The client state 8 Handling changes in state 9 The side effect model 10 A speed tour of MobX 12 An observable state 12 Observing the state changes 13 It's time to take action 14 A comparison with Redux 16 Redux in a nutshell 16 MobX versus Redux 17 Summary 21 Chapter 2: Observables, Actions, and Reactions 22 Technical requirements 22 Observables 23 Creating observables 24 Observable arrays 26 Observable maps 27 A note on observability 28 The computed observable 29 Better syntax with decorators 31 Actions 33 Enforcing the use of actions 34 Decorating actions 35 Reactions 37 autorun() 37 reaction() 39 A reactive UI 41 when() 43 when() with a promise 44 Quick recap on reactions 45 Summary 46 Chapter 3: A React App with MobX 47 Technical requirements 47 The book search 47 Observable state and actions 49 Managing the async action 51