Book Image

MobX Quick Start Guide

By : Pavan Podila, Michel Weststrate
Book Image

MobX Quick Start Guide

By: Pavan Podila, Michel Weststrate

Overview of this book

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.
Table of Contents (17 chapters)
Title Page
Dedication
Packt Upsell
Foreword
Contributors
Preface
Index

Actions


Although you can change an observable directly, it is highly recommended that you use actions to do it. If you remember, in the previous chapter, we saw that actions are the ones that cause a state-change. The UI simply fires the actions and expects some observables to be mutated. Actions hide the details of how the mutation should happen or what observables should be affected.

The diagram below is a reminder that UI can modify the State only via an Action:

Actions introduce vocabulary into the UI and give declarative names to the operations that mutate the state. MobX embraces this idea completely and makes actions a first-class concept. To create an action, we simply wrap the mutating function inside the action() API. This gives us back a function that can be invoked just like the original passed-in function. Take a look at this code block:

import { observable, action } from 'mobx';

const cart = observable({
items: [],
modified: new Date(),
});

// Create the actions
const addItem...