DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Trending

  • Tomorrow’s Cloud Today: Unpacking the Future of Cloud Computing
  • Auto-Scaling Kinesis Data Streams Applications on Kubernetes
  • 13 Impressive Ways To Improve the Developer’s Experience by Using AI
  • Explainable AI: Making the Black Box Transparent
  1. DZone
  2. Coding
  3. JavaScript
  4. MobX in React

MobX in React

Atishay Khare user avatar by
Atishay Khare
·
Dec. 26, 19 · Tutorial
Like (3)
Save
Tweet
Share
18.65K Views

Join the DZone community and get the full member experience.

Join For Free

MobX is the new, upcoming state management solution. This blog is all about how to create a simple React-Native app using MobX.

MobX is faster than Redux, easier to learn, and requires less boilerplate code.

Main Concepts

Stores

Stores create data sources. A store is basically an ES6 class. The state is automatically derived from a data source by MobX by using ES6 decorators.

  1. The store can expose the observable field(s), to which an observer can react.
  2. The store can additionally expose some derived observable fields too. Which are pure functions on observable fields? MobX calls them as computed fields.
  3. The store can also change the values of observable fields via actions. Only in this way MobX can allow you to change state.
You may also like: How to Structure Your MobX App for the Real World.

Observables

Observables extend functionality to subscribe to their changes. We can list down our class properties with the @observable decorator, and, using observers, check their values.

These observers will be updated accordingly every time the values will change.

Computed Values

Computed values are derived from observables. These values will be automatically updated when the observables will change.

It should be kept in mind that, ‘computed’ has to be observed in order to be updated

Reactions

Reactions are identical to computed values, but they are used to produce side-effects instead of returning new value (patching DOM, making network requests, etc.).

MobX provides three reaction functions when, autorun, and reaction.

When — when takes two functions: predicate and effect. It executes and checks predicate until it returns true; it then executes the effect function. After that, it disposes and stops reacting to the checked property.

Autorun — autorun is used in specific cases where you want a reactive function that will get fired every time the checked value is updated. Unlike computed it doesn’t have to be checked itself.

Reaction — reaction is like autorun but gives you more control over what properties to check. It takes two functions,  data-function and side-effect-function. The data-function is observed and returns data that is used in side-effect-function.

Actions

Actions are responsible for altering the state.we can use them to explicitly mark that function with @action decorator.

This decorator takes a function and wraps it into a transaction, untracked and allows state changes.

Transaction — The transaction is used to batch together updates in the state, so until and unless that function is completed, no observers will be notified. So, we can update various properties at once.

Untracked — With the help of untracked, we can run code without establishing observers (just like reactions, or unlike computed’s)

Allow State Changes — Allow state changes is used to allow or reject state changes for certain functions. By default allows an action to make changes (and disallows them for computed and observer).

Observers

Honestly,  observers aren’t part of MobX core. They are provided by the mobx-react package. They are used to enable views to “observe” observables and re-render on change.

Let’s explore a simple ValueStore. It provides an observable field named count value and actions increase_value and decrease_value to change the value.

JavaScript




x
43


 
1
// @ flow
2
import {observable,action} from “mobx”;
3
 
          
4
class ValueStore{
5
     @observable countValue=0;
6
 
          
7
     @action increase_value()={
8
         this.countValue+=1;
9
       }
10
  
11
     @action decrease_value()={
12
         this.countValue-=1;
13
       }
14
}
15
 
          
16
export default ValueStore;
6
 
          



Here is a look at a component that keeps track of count value and re-renders every time the count value gets changed.

JavaScript




xxxxxxxxxx
1
33


 
1
// RN imports
2
import { observer, inject } from "mobx-react";
3
 
          
4
@inject("valueStore")
5
@observer
6
class Counter extends Component {
7
 
          
8
  render() {
9
      return <Text>Count:  {this.props.valueStore.count}</Text>;
10
  }
11
}
4
 
          



By decorating class with  @observer, MobX can infer reactions to the changes in store and automatically subscribe to them and re-render component on getting changes.

@inject is a MobX decorator that will provide component props with the mentioned store.

MobX provides a React Provider that can be made as a parent component for all the components of your application. A MobX provider should be initialized with all the stores that you may want to be injected into your components.

JavaScript
xxxxxxxxxx
1
41
 
1
import { Provider } from "mobx-react";
2
 
          
3
class App extends Component {
4
  render() {
5
    
6
     return (
7
      <Provider {counterStore: new ValueStore(), userStore:      new UserStore()}>
8
            <Home />
9
      </Provider>
10
    );
11
 }
12
}
13
 
          
14
export default App;


Now, all children of the Home component can be injected with value stores and user stores.


Further Reading

  • Everything React: Tutorials for Beginners and Experts Alike.
  • Introduction to Redux.
  • Learn the Basics of Redux for React.
React (JavaScript library)

Published at DZone with permission of Atishay Khare. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Tomorrow’s Cloud Today: Unpacking the Future of Cloud Computing
  • Auto-Scaling Kinesis Data Streams Applications on Kubernetes
  • 13 Impressive Ways To Improve the Developer’s Experience by Using AI
  • Explainable AI: Making the Black Box Transparent

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: