26th Jul 2022

Introduction to MobX with React Native

Mean

Written By, Hetal Shukla

Overview

  • Mobx is a state management library that can be used with any JavaScript framework.
  • MobX is a simple, scalable and powerful state management solution.
  • MobX is a standalone library.
  • MobX provides the mechanism to store and update the application state that react-native then uses to render the components

mobx-with-react-native-intro

Core Concept Of MobXs

  • Observales: Defines a trackable field that stores the state.
  • Actions: Marks a method as action that will modify the state.
  • Reactions: Marks a getter that will derive new facts from the state and cache its output.

Observable

Observables in MobX allow us to add observable capabilities to our data structures like: classes, objects, arrays and make our property observables.

Make Observable

It can be used to track existing object properties and make them observable.

Example: I have created variable called data, type of array we can easily create an observable by using the observable decorator.

Actions

An action is a function which can change the observable data.

MakeObsevable:- It can be used to track existing object properties and make them observable.

Example:
I have created userdata Action which calls api to fetch user data.By using action we can make changes in the observable data.

Use of Class objects in Store

Here you can see I have imported the store file and used a Demo class object.
E.g : Demo.UseData()
This Userdata action is calling an API and we can directly pass the data in the main file.

So, here I have passed Demo.data directly in flatlist data so it will take data from the store automatically and execute it.

API Call flow works in MobX

Computed

  • Marks a getter that will derive new facts from the state and cache and its output.

RunInAction

  • Use this utility to create a temporary action that is immediately invoked.

Autorun

  • The autorun function accepts one function that should run every time anything it observes changes.

Mobx Vs Redux

  • MobX has big differences from Redux.
  • For Example using Redux we can only have one single store where we store all our state data.
  • Using MobX we can have multiple stores for different purposes.
  • Using Redux, our state is immutable, while in MobX we can mutate our state.

Happy Learning.!!!

Written By,

React Native Developer at Yudiz Solutions Pvt. Ltd