EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

MobX React Native

By Rahul DubeyRahul Dubey

Home » Software Development » Software Development Tutorials » React Native Tutorial » MobX React Native

MobX React Native

Introduction to MobX React Native

For any React Application, State Management is an important aspect. React is a UI Library so we need state management to take care of the state of the application. Sometimes, State Management is quite problematic as its quite easy to develop a React Application with an inconsistent State and it will be quite difficult to handle. In this article we will understand MobX as a State Management solution for a React Native Application. MobX is used with any JavaScript Framework as a State Management Library. React and MobX are quite powerful when used together and correctly. React Native uses MobX’s mechanism of storing and updating the application state to render its components. The idea of MobX is to check the minimal state, derive it, and to never change the state into more states.

Concept of MobX

MobX has three concepts which are listed below:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  1. Observables
  2. Actions
  3. Reactions

Introduction to MobX React Native

1. Observables

Observables keep the core state of the application. It is used to create an object which can perform new changes to which the user can react. The idea is to make an object able to emit new changes to which the observer can react. It can be done using a @observable decorator.

Below is an example where we have a variable named counter which changes over time.

import { observable } from
"mobx", class Store {
@observable counter = 0;
}
export default new Store();

2. Computed Observables

The values which are produced from earlier defined observables are called computed values. MobX doesn’t allow the creation of more states. Let’s take an example where our counter variable was holding the number of minutes by which a flight gets delayed. Now, we will add a computed delay message which is derived from the observable counter.

import { observable, computed } from
"mobx", class Store {
@observable counter = 0;
@computed get delayMessage = () => {
return 'The flight is delayed by' + this.count;
};
}
export default new Store();

Popular Course in this category
React JS Redux Training (1 Course, 5 Projects)1 Online Courses | 5 Hands-on Projects | 18+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,487 ratings)
Course Price

View Course

Related Courses

The above mentioned @computed works as a function that automatically changes the delayed message every time the value of counter changes.

3. Actions

Actions are functions that modify the state. Uni-Directional data flow is supported by MobX which means that every time the state of the action changes, it updates each and every view which is related to the state. We will add an action that updates according to the counter variable whenever the delay increases.

Store {
import { observable
, action
, computed } from "mobx";
class Store {
@observable counter = 0;
@computed get delayMessage = () => {
return 'The flight is delayed by' + this.count;
};
@action
updateDelay = delay => { this.counter = delay;
};
}
export default new Store();

Examples

We are going to develop an app that fetches images from Unsplash and displays it to the user. Our application is going to use Unsplash API for fetching images. The API can be generated here.

Step 1:

We will be searching for random images and will save the results. Then will allow the user to add the image to favorites.

import { action, observable ,decorate } from "mobx";
class Store {
text = '';
updateText = (text) => { this.text = text;
}
data = null; searchImages = () => {
fetch(`https://api.unsplash.com/search/photos?client_id=${API_KEY}&page=1&query=${this.text}&o rientation=landscape`)
.then(response => response.json())
.then(data => this.setData(data));
};
setData = (data) => { this.data = data;
};
}
decorate(Store, { text: observable, updateText: action, data: observable, searchImage: action, setData: action,
});
export default new Store();

Step 2:

We will create a component PictureList.js which is going to render the list of images. It will also display the pictures added to favorites.

import React from "react";
import { TextInput, Button, FlatList, View } from 'react-native'; import { inject, observer } from "mobx-react";
function PictureList(props) {
const { text, updateText, data, searchImages } = props.store; return (
<>
<TextInput style={styles.input} value={text} onChangeText={updateText}
/>
<Button title="Search"
style={styles.button}
onPress={searchImages}
/>
/>
<FlatList data={data.results}
keyExtractor={(item) => item.id} renderItem={({ item }) => (
<ImageView
source={{ uri: item.urls.small }} onPress={() => {}}
/>
)}
/>
</>
);
}
export default inject("store")(observer(PictureList));

Step 3:

import { action ,decorate, observable } from "mobx"; class Store {
text = '';
updateText = (text) => {...}; data = null;
searchImages = () => {...};
setData = (data) => {...}; favorites = [];
addToFavorite = (image) => { this.favorites.push(image); this.data = null;
this.text = '';
};
}
decorate(Store, { text: observable, updateText: action, data: observable, searchImage: action, setData: action,
favorites: observable, addToFavorite: action,
});
export default new Store();

We are going to update the View for the newly added Observables and actions. Previously searched pictures will be erased.

const { favorite, addToFavorite} = this.props.store return (
<>
{data?
<FlatList style={styles.container}
data={data.results}
keyExtractor={(item) =>
item.id} renderItem={({ item })
=> (
<ImageView
source={{ uri: item.urls.small }}
onPress={() => addToFavorite(item.urls.small)}
/>
)}
/> :
<FlatList
style={styles.container}
data={favorites}
keyExtractor={(item, index) =>
index.toString()} renderItem={({ item }) => (
<ImageView
source={{ uri: item }} // render favorite images
/>
)}
/>
}
</>
);
import { computed ,decorate, action, observable } from
"mobx"; class Store {
get getFavoriteCount() {
return
this.favorites.length;
}
}
decorate(Store, { getFavoriteCount: computed,
});
export default new Store();

const { getFavoriteCount } =
this.props.store; return (
<Text style={styles.count}>
Images added:
{getFavoriteCount}
</Text>
data={data.results}
keyExtractor={(item) => item.id} renderItem={({ item }) => (
<ImageView
source={{ uri: item.urls.small }}
onPress={() => addToFavorite(item.urls.small)}
/>
)}
/> :
<FlatList style={styles.container} data={favorites}
keyExtractor={(item, index) => index.toString()} renderItem={({ item }) => (
<ImageView
source={{ uri: item }} // render favorite images
/>
)}
/>
}
</>
);
import { computed ,decorate, action, observable } from "mobx"; class Store {
get getFavoriteCount() { return this.favorites.length;
}
}
decorate(Store, { getFavoriteCount: computed,
});
export default new Store();

const { getFavoriteCount } = this.props.store; return (
<Text style={styles.count}> Images added: {getFavoriteCount}
</Text>>
);

At last, we will provide the store to the root component.

import React from 'react';
import PictureList from './src/container/PictureList'; import { Provider } from 'mobx-react';
import store from './src/store'; const App = () => {
return (
<Provider store={store}>
<PictureList />
</Provider>
);
};
export default App;

Output:

Output 1

Output 2

Conclusion – MobX React Native

In this article, we understood how State Management is necessary for any application. We understood how MobX and React are powerful when they are used together. MobX makes State Management easy and hassle-free. In this article, we got to know about observables, Computed Observables, Actions, and Reactions. At the end, we went through an example in which we fetched different pictures from Unsplash, managed the state of the application, and understood how a user can add pictures to favorites and we can keep a count on it. I hope this article would have cleared some concepts on MobX.

Recommended Articles

This is a guide to MobX React Native. Here we discuss the Introduction of MobX React Native along with examples. You may also have a look at the following articles to learn more –

  1. Mobx vs Redux
  2. React Native Image
  3. React Native State
  4. React Native Architecture

React JS Redux Training (1 Course, 4 Projects)

1 Online Courses

5 Hands-on Projects

18+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
React Native Tutorial
  • Basic
    • What is React Native?
    • React Versions
    • React Constructor
    • React Native Architecture
    • React Native Libraries
    • React Components Libraries
    • React Native Components
    • React Component Library
    • React Component Lifecycle
    • React Native Framework
    • React Higher Order Component
    • React Ternary Operator
    • React Native Charts
    • React Native Layout
    • React Native Grid
    • React Native Fetch
    • React Native Modal
    • React Native SVG
    • Button in React Native
    • React List Components
    • React Native Element
    • React Native FlatList
    • React Native SectionList
    • react native dropdown
    • React Native Menu
    • React Native State
    • React State Management
    • React Native Tabs
    • React Native Tab Bar
    • React Format
    • React-Native Switch
    • React Native Firebase
    • React Native Flexbox
    • React Native StatusBar
    • React Native ScrollView
    • React Native ListView
    • React Native TextInput
    • React Native Table
    • React-Native Border Style
    • React Native Search Bar
    • React-Native StyleSheet
    • React Native Vector Icons
    • React Native Login Screen
    • React Native Splash Screen
    • React Native Image Picker
    • React Native Navigation
    • React Native Swift
    • React Controlled Input
    • React Fragment
    • React Native Color
    • React Portals
    • React Refs
    • React shouldComponentUpdate()
    • React ComponentDidMount()
    • React componentWillUpdate()
    • React Native Orientation
    • React Native Animation
    • React Native Form
    • React Props
    • React Native Linear Gradient
    • React Native AsyncStorage
    • React Error Boundaries
    • React Native Progress Bar
    • React-Native Calendar
    • React Native Linking
    • React Native DatePicker
    • React Native Image
    • React Native Drawer
    • React Native Drawer Navigation
    • React Native Fonts
    • React Native Overlay
    • React Native OneSignal
    • React Native Template
    • React Native Router
    • React Router Transition
    • React Dispatcher
    • React Native Redux
    • React JSX
    • React native keyboardavoidingview
    • React Native Permissions
    • React Redux Connect
    • React Native Material
    • React Native Gesture Handler
    • React Native Theme
    • React Native Accessibility
    • React Native Justify Content
    • MobX React Native
    • React Native Authentication
    • React Native UUID
    • React Native Geolocation
    • React Native Debugger
    • React Native Carousel
    • React Native Local Storage
    • React Native TypeScript
    • React Bootstrap
    • React Native SQLite
    • React Native Interview Questions
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - React JS Redux Training (1 Course, 4 Projects) Learn More