MobX
Simple, scalable state management for React Component

React
React is a JavaScript library for creating user interfaces

React Main Concepts
- React is only concerned about rendering View/UI
- React uses a Virtual DOM to high performance
- React introduces one-way reactive data flow

view as Components reder DOM
argument/properties as Props
private data as States of component
Then What is MobX for!!

Complex components Hierarchy

MobX

State Management Solution for React component

@action
Actions are anything that modify the state
import $ from 'jquery';
import store from '../store/index';
@action getSearchResults () {
$.ajax({
method: 'GET',
url: store.getSearchApiUrl
}).done((response) => {
store.setSearchResult(response.data.results);
});
}
@Observable
@observable classProperty = value
@observable search = (searchText) ? searchText : '';
@observable order = 'desc';
@observable total = 0;
@observable searchResults = [];
@observable isReloadResult = false;
@Observer
Component Class as a observer

@observer
class Results extends Component {
constructor(props) {
super(props);
loadSearchResults();
}
...........
}
@Computed
Manipulated @observable variable
@computed get getSearchApiUrl() {
var URL = this.SEARCH_API_URL + 'order=' + this.order, params;
params = (this.search) ? '&q=' + this.search : '';
params = (this.type) ? params + '&type=' + this.type : params;
params = (this.selectedTag) ? params + '&tag=' + this.selectedTag : params;
URL = URL + params;
return (this.searchResults.length && !this.isReloadResult)
? URL + "&page=" + this.nextPage : URL ;
}
$.ajax({
method: 'GET',
url: store.getSearchApiUrl
})
@autorun
Run related events or tasks when observable value changed
var numbers = observable([1,2,3]);
var sum = computed(() => numbers.reduce((a, b) => a + b, 0));
var disposer = autorun(() => console.log(sum.get()));
// prints '6'
numbers.push(4);
// prints '10'
Alternatives for State management
Example Code: https://github.com/emran/react-mobx-phonebook
Pros
- Easy to Use
- Small Learning curve
- Writing Code is faster
Cons
MobX
- MobX have some Magic
- Not everything is in your hand

A
n
y
Q
u
e
s
t
i
o
n
Md. Emran Ul Hadi
Software Engineer
P1, Bashundhara Group

MobX - state management for react component
By Emran Ul Hadi
MobX - state management for react component
- 1,515