React Native — Redux

Ahmad Hizbullah
5 min readJan 23, 2021

--

React Native adalah framework Javascript, yang sebenarnya merender aplikasi mobile untuk iOS dan android. React Native ini berbasis pada Ract, library Javascript oleh Facebook, untuk membangun user interfaces, tapi tidak menargetkan browser, namun platform mobile.

Redux merupakan state management library, yang dapat digunakan oleh berbagai framework dan library seperi React dan React Native. Tujuan utama menggunakan redux adalah karena dapat digunakan untuk menjadi satu application state as global state dan dapat berinteraksi dengan stete dari bebagai component react lain, dimana sangat mudah apakah itu meruapakan parent child maupun siblings.

Dasar dari penggunaan Redux ini datang dikarenakan terdapat aplikasi yang memiliki sistem yang kompleks dan besar.

Redux bisa kita bagi lagi menjadi beberapa section.

  1. Actions, merupakan payload yang berisi informasi untuk mengirimkan data dari aplikasi ke store. Bagian ini hanya berisi informasi untuk store. Ini berarti apabila terdapat state yang state yang diharuskan berubah, maka akan merubah kebutuhan, kemudian akan dikirim melalui actions
  2. Reducers, Apabila aplikasi dikirim untuk perubahan state, maka tanggung jawab reducers perlu merubah state dan mengembalikan state baru di aplikasi.
  3. Store, membantu reducers store makan dapat terbuat, yang memegang semua state diaplikasi, itu lalu akan direkomendasikan untuk menggunakan singrl store untuk semua aplikasi kemudian memiliki beberapa stores yang akan melanggar penggunaanaan redux yang hanya memiliki single store
  4. Components(UI), ni merupakan UI aplikasi
  5. Middlewares, dapat digunakan untuk bermacam-maccam, memasukan asyncronous API calls. Suara middleware lebih kompleks daripada yang terlihat.

Step 1: Create Basic React native

react-native init projectName

Step 2: Running app on your devices

Untuk cek adb apakah sudah aktif

adb devices

running on android

react-native run-android

running on iOS

react-native run-ios

Step 3: Add simple counter into the App.js

App.js merupakan file yang mengandung UI yang dibutuhkan untuk merender di aplikasi dengan memungkinka styling.

Buka file App.js, kemudian isikan kodingan simple counter number, seperti berikut

import React, { Fragment, Component } from ‘react’;
import {
SafeAreaView,
StyleSheet,
View,
Button,
Text
} from ‘react-native’;

class App extends Component {
state = { count: 0 };
decrementCount() {
let { count } = this.state;
count++;
this.setState({
count
})
}
incrementCount() {
let { count } = this.state;
count++;
this.setState({
count
})
}
render() {
const { count } = this.state;
return (
<View styles={styles.container}>
<Button
title=”increment”
onPress={() => this.incrementCount()}
/>
<Text>{count}</Text>
<Button
title=”decrement”
onPress={() => this.decrementCount()}
/>
</View>
);
}
};

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: ‘center’,
alignItems: ‘center’
}
});

export default App;

Maka tampilan akan seperti ini

Step 4: Install the necessary package to connect your app with redux

Untuk yarn

yarn add react-redux
yarn add redux

Untuk npm

npm install react-redux
npm install redux

Step 5: Create the necessary folders inside root

Folder yang perlu dibuat untuk kebutuhan implementasi Redux adalah:

  1. actions => counts.js
  2. constants => index.js
  3. reducers => countReducer.js
  4. components => configureStore.js

Step 6: Create Actions and Reducer function

6.1 Didalam folder constants. Buat satu file bernama index.js kemudian isikan kodingans sperti dibawah

export const COUNTER_CHANGE = ‘COUNTER_CHANGE’

6.2 Didalam folder actions buat file baru bernama counts.js. Untuk actions sendiri merupakan jaascript objects yang merepresentasikan palyloads (muatan) informasi that can send data dari aplikasi, ke Redux store.

Actions memiliki type and optional payload. Di cas ini, type akan Counter_Change, dan payload adalah count yang mana akan kita ssigning ke our count variable di store.

Pada file counts.js ini kita kemudian tambahkan kodingan yang berisi sebagai berikut.

import { COUNTER_CHANGE } from ‘../constants’;
export function changeCount(count) {
return {
type: COUNTER_CHANGE,
payload: count
}
}

untuk changeCount() meruakan function yang mengembalikan action. sekarang berdasarkan action, reducers function’s case is executed.

Tapi, kita membutuhkan untuk connect ke action ke App.js component. Kemudian kita tidak dapat menambahkan data into the Redux store. Kemudian pertama kita membutuhkan create a store. Tapi seblum itu kita juga membutuhkan reducer function. Jadi, pertama buat reducer -> create a store -> connect the React Native application to the Redux store.

6.3 Didalam reducers function, buat countReducer.js. Reducer merupakan pure function, yang mengambil state dan action sebelumnya sebagai arguments and returns a new state. Reducer merupakan instrumen yang menjaga current state of count updated melalui our app yang berubah.

import { COUNTER_CHANGE } from ‘../constants’;
const initialState = {
count: 0
};
const countReducer = (state = initialState, action) => {
switch(action.type) {
case COUNTER_CHANGE:
return {
…state,
count:action.payload
};
default:
return state;
}
}
export default countReducer;

Disini kita memiliki defined the functional called countReducer yang menerima dua arguments

  1. state
  2. action

Pertama, it will take initial state pada aplikasi, lalu pass argument apapun. it takes that argument lalu mengoperasikan berdasakan case execution. Argment kedua adalah action, yang berfokus pada type dan payload. Payload di count value, which asssigned to count variable di store.

Step 7: Create Redux Store.

Didalam root folder, create one folder called store and inside this folder add one file called configureStore.js add the following code.

import { createStore, combineReducers } from ‘redux’;
import countReducer from ‘../reducers/countReducer’;
const rootReducer = combineReducers(
{ count: countReducer }
);
const configureStore = () => {
return createStore(rootReducer);
}
export default configureStore;

Disini kita akan membuat redux store and passed the reducer to dthat store. This store will ideally contain all the data that handles the app state. The combineReducer function, mengkombinasikan sema reducers yang berbeda kedalam satu dan forms the global state. So this is the global state of our state of our whole app.

Step 8: Pass the Store the React Native app

Inside the root folder, you will find one file called index.js and inside that file add following code.

import { AppRegistry } from ‘react-native’;
import React from ‘react’;
import App from ‘./App’;
import { name as appName } from ‘./app.json’;
import { Provider } from ‘react-redux’;

import configureStore from ‘./store/configureStore’;

const store = configureStore()

const RNRedux = () => (
<Provider store = { store }>
<App />
</Provider>
)

AppRegistry.registerComponent(appName, () => RNRedux);

Ini hampir sama seperti React web app, in which we pass the Provider as a rot element and pass the store and then via react-redux’s connect() function , Kita dapat connect ke berbagai react compnent to redux store

Step 9: Connect React Native app to Reduc astore

Finally, we connect our App.js component to the Redux store. Untuk itu, kta membutuhkan connect() function from the react-redux libr.

import React, { Component } from ‘react’;
import {
StyleSheet,
View,
Button,
Text
} from ‘react-native’;
import { connect } from ‘react-redux’;
import { bindActionCreators } from ‘redux’;
import * as countActions from ‘./actions/counts’;

class App extends Component {
decrementCount() {
let { count, actions } = this.props;
count — ;
actions.changeCount(count);
}
incrementCount() {
let { count, actions } = this.props;
count++;
actions.changeCount(count);
}
render() {
const { count } = this.props;
return (
<View styles={styles.container}>
<Button
title=”increment”
onPress={() => this.incrementCount()}
/>
<Text style={styles.textCenter}>{count}</Text>
<Button
title=”decrement”
onPress={() => this.decrementCount()}
/>
</View>
);
}
};

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: ‘center’,
alignItems: ‘center’
},
textCenter:{
textAlign :’center’
}
});

const mapStateToProps = state => ({
count: state.count.count,
});

const ActionCreators = Object.assign(
{},
countActions,
);
const mapDispatchToProps = dispatch => ({
actions: bindActionCreators(ActionCreators, dispatch),
});

export default connect(mapStateToProps, mapDispatchToProps)(App)

Step 10: Test your app

sc: https://enappd.com/blog/redux-in-react-native-app/92/

--

--