Use of Redux in React Native

Neha Sharma
codewave technologies
9 min readDec 26, 2019

--

In this article we will learn what is Redux, how to use Redux in React Native with a sample project.

When I stated using React Native for mobile app development, I found it very interesting but I feel it is incomplete without Redux.

Then I stated looking for some tutorials or examples for Redux in React Native. For me, it was very hard to understand the functionality of actions, reducers, store, middleware in Redux without working on them.

So, I started creating some sample projects to understand the concept of Redux . This guide is built on my learnings and should help anyone understand the most powerful tool in React Native.

Let’s get started……

What is Redux?

Redux is state management tool. With the help of Redux, all state in your application are kept in store and that can be accessible from all components.

Why do we need Redux?

As your application become big & more complex, it’s hard to mange your states & pass data from one component to other components or child components. This is where Redux helps - Giving global access to state or data which can be used in any component without depending on other components.

What are the different sections in Redux?

Redux can be broken into following sections & each section has their own functionality.

Actions: are used to send data (payload information) from your application to store i.e if you are making any changes in data, that will be dispatched through action and updated in store. Also there is only one access point to store which can only be accessed by Actions.

Reducers: After Action, next in line is Reducers whose main role is to update the necessary changes to states and return the new state with updated value.

Store: It is a place which keeps or hold all states together in your application. It is always recommended to use single store in your application

Components: where you kept your User interface (UI).

Middleware: are functions which allow us to extent the functionality of Redux in our application. Middleware sits between dispatch action & reducer, which means we can execute some other function before dispatch reaches to reducer. In our sample project, we are using logger as a middleware, which will give us the details of previous state, action trigger & updated state.

Ok, Let’s get going with the sample example on Redux. In this example we will fill employee details, store employee details in Redux & show them on next screen.

  1. Create a new project
react-native init ReduxExample

2. Install React Navigation & Gesture Handler

npm install react-navigation
npm install --save react-native-gesture-handler

3. Add Redux

npm install --save redux

4. Create necessary folders in your app

Actions
Reducers
Store
Screens (in this folder we will keep UI related js files)

5. Create EmployeeDetail.js file in your Screen folder.

import React from "react";import {View, Text,StyleSheet, SafeAreaView,TextInput,TouchableHighlight} from "react-native";import {connect} from "react-redux"class EmployeeDetails extends React.Component{constructor(props){super(props)this.state = {name:"",schoolName:"",companyName:""}}render(){return(<SafeAreaView style={styles.container}><View style={styles.mainView}><Text style={styles.mainTextStyle}>Submit Employee Details</Text><Text style={styles.textStyle}>Enter Your Name</Text><TextInputstyle={styles.textInputStyle}underlineColorAndroid="transparent"placeholderTextColor="#cccccc"placeholder="Enter Your Name"onChangeText={name => {this.setState({ name: name }, () => {});}}/><Text style={styles.textStyle}>Enter Your School Name</Text><TextInputstyle={styles.textInputStyle}underlineColorAndroid="transparent"placeholderTextColor="#cccccc"placeholder="Enter Your School Name"onChangeText={schoolName => {this.setState({ schoolName: schoolName }, () => {});}}/><Text style={styles.textStyle}>Enter Your Company Name</Text><TextInputstyle={styles.textInputStyle}underlineColorAndroid="transparent"placeholderTextColor="#cccccc"placeholder="Enter Your Company Name"onChangeText={companyName => {this.setState({ companyName: companyName }, () => {});}}/><TouchableHighlightunderlayColor="transparent"style={styles.buttonStyle}onPress={() => {//Here we will call our Action}}><Text style={styles.buttonTextStyle}>Submit</Text></TouchableHighlight></View></SafeAreaView>)}}const styles = StyleSheet.create({container: {flex: 1,width: "100%",height:"100%",justifyContent: 'flex-start',alignItems: 'center',backgroundColor:"lightgray",//   paddingHorizontal:10,paddingBottom:50},mainView:{width:"100%",height:"50%",justifyContent: "flex-start",alignItems: "center",padding:20,},textInputStyle:{width:"100%",height:40,backgroundColor:"white",paddingHorizontal:15,marginBottom:10,marginTop:10},textStyle:{width:"100%",height:20,//paddingHorizontal:15,textAlign:"left",marginTop:10,fontSize:15},mainTextStyle:{width:"100%",height:40,//paddingHorizontal:15,textAlign:"center",marginTop:10,marginBottom:10,fontSize:20},buttonStyle:{width: "100%",height: 40,borderRadius: 5,justifyContent: "center",alignItems: "center",backgroundColor: "white",marginTop:20},buttonTextStyle:{width:"100%",height:"100%",textAlign:"center",marginTop:10,fontSize:18},})export default EmployeeDetails;

So this is the basic application on which we are working.

As you can see, I have not added any action on Submit button.

Now we will add action, reducer and will save employee data in store using connect function.

The connect() function connects a React component to a Redux store.

6. Create a saveEmployeeDetailAction.js in Action folder

export const saveEmployeeDetails = (employeeDetails) =>({type:"SAVE_EMPLOYEE_DETAIL",employeeDetails:{name:employeeDetails.name,schoolName:employeeDetails.schoolName,companyName:employeeDetails.companyName}});

In this file, we mention type & payload. employeeDetails is a payload which contain some information like name, schoolName & companyName of employee. SAVE_EMPLOYEE_DETAIL is a type here, using this type we will add employee details in store through Reducer.

7. Create employeeDetailReducer.js in Reducer folder

const initialState = {employeeDetails: {name:"",schoolName:"",companyName:""}};const employeeDetailReducer = (state = initialState , action) => {switch(action.type){case "SAVE_EMPLOYEE_DETAIL" :{return{...state,employeeDetails : action.employeeDetails}}default:{return state;}}}export default employeeDetailReducer;

A reducer is a pure function that takes the previous state and an action as arguments and returns a new state

Reducer have two thing state & action. It will take the initial state of our application, and then we pass argument, it takes that argument and operates based on the switch case execution. The second argument is action, which consists of type and payload. The payload is the employeDetail , which assigned to employeeDetails in store.

Remember here — we have returned a new state and not existing state. So we have modified the state in pure manner.

8. Create store.js file in Store folder

// Imports: Dependenciesimport AsyncStorage from '@react-native-community/async-storage';import { createStore, applyMiddleware } from 'redux';import { createLogger } from 'redux-logger';import { persistStore, persistReducer } from 'redux-persist';import rootReducer from '../reducers/index';// Middleware: Redux Persist Configconst persistConfig = {key: 'root',storage: AsyncStorage,whitelist: ["employeeDetailReducer"],blacklist: [],};const persistedReducer = persistReducer(persistConfig, rootReducer)const store = createStore(persistedReducer,applyMiddleware(createLogger(),),);let persistor = persistStore(store);export {store,persistor,};

In Store file, I have used persistStore & createLogger as a Middleware.

persistStore: Using persistStore we can save our data in offline mode & for that you have to mention that reducer name in whitelist.

createLogger: will give you information about your previous state, action dispatch & next state(updated value).

9. Pass store to React Native in App.js file

import React from 'react';import { PersistGate } from 'redux-persist/es/integration/react'import { Provider } from 'react-redux';import AppNavigator from "./screens/Navigation/Navigation";import { store, persistor } from './redux/store/store';export default App = () => {return (// Redux: Global Store<Provider store={store}><PersistGateloading={null}persistor={persistor}><AppNavigator/></PersistGate></Provider>);};

Now let’s connect Redux to our EmployeeDetail.js file, for this we need to add mapDispatchToProps function.

10. First, import your action in EmployeeDetail.js file

import {saveEmployeeDetails} from "../redux/actions/saveEmployeeDetailsAction"

11 . Now for submit button action, you have to add dispatch action in mapDispatchToProps, like this

const mapDispatchToProps = (dispatch) => {return{reduxSaveEmployeeDetail:(employeDetails) => dispatch(saveEmployeeDetails(employeDetails))}}

12 . Now use reduxSaveEmployeeDetail action onClick of submit button.

<TouchableHighlightunderlayColor="transparent"style={styles.buttonStyle}onPress={() => {var employeeDetails = {};employeeDetails.name = this.state.name;employeeDetails.schoolName = this.state.schoolName;employeeDetails.companyName = this.state.companyName;this.props.reduxSaveEmployeeDetail(employeeDetails)
this.props.navigation.navigate("ShowEmployeeDetail")
}}><Text style={styles.buttonTextStyle}>Submit</Text></TouchableHighlight>

Here, I am passing employee details as an object, & navigating to ShowEmployeeDetails.js to show entered data using redux.

13 . Now add mapDispatchToprops to connect.

export default connect(null,mapDispatchToProps)(EmployeeDetails);

Now Our EmployeeDetails.js file combine code will like:

import React from "react";import {View, Text,StyleSheet, SafeAreaView,TextInput,TouchableHighlight} from "react-native";import {connect} from "react-redux"import {saveEmployeeDetails} from "../redux/actions/saveEmployeeDetailsAction"class EmployeeDetails extends React.Component{constructor(props){super(props)this.state = {name:"",schoolName:"",companyName:""}}render(){return(<SafeAreaView style={styles.container}><View style={styles.mainView}><Text style={styles.mainTextStyle}>Submit Employee Details</Text><Text style={styles.textStyle}>Enter Your Name</Text><TextInputstyle={styles.textInputStyle}underlineColorAndroid="transparent"placeholderTextColor="#cccccc"placeholder="Enter Your Name"onChangeText={name => {this.setState({ name: name }, () => {});}}/><Text style={styles.textStyle}>Enter Your School Name</Text><TextInputstyle={styles.textInputStyle}underlineColorAndroid="transparent"placeholderTextColor="#cccccc"placeholder="Enter Your School Name"onChangeText={schoolName => {this.setState({ schoolName: schoolName }, () => {});}}/><Text style={styles.textStyle}>Enter Your Company Name</Text><TextInputstyle={styles.textInputStyle}underlineColorAndroid="transparent"placeholderTextColor="#cccccc"placeholder="Enter Your Company Name"onChangeText={companyName => {this.setState({ companyName: companyName }, () => {});}}/><TouchableHighlightunderlayColor="transparent"style={styles.buttonStyle}onPress={() => {var employeeDetails = {};employeeDetails.name = this.state.name;employeeDetails.schoolName = this.state.schoolName;employeeDetails.companyName = this.state.companyName;this.props.reduxSaveEmployeeDetail(employeeDetails)this.props.navigation.navigate("ShowEmployeeDetail")}}><Text style={styles.buttonTextStyle}>Submit</Text></TouchableHighlight></View></SafeAreaView>)}}const styles = StyleSheet.create({container: {flex: 1,width: "100%",height:"100%",justifyContent: 'flex-start',alignItems: 'center',backgroundColor:"lightgray",paddingBottom:50},mainView:{width:"100%",height:"50%",justifyContent: "flex-start",alignItems: "center",padding:20,},textInputStyle:{width:"100%",height:40,backgroundColor:"white",paddingHorizontal:15,marginBottom:10,marginTop:10},textStyle:{width:"100%",height:20,textAlign:"left",marginTop:10,fontSize:15},mainTextStyle:{width:"100%",height:40,//paddingHorizontal:15,textAlign:"center",marginTop:10,marginBottom:10,fontSize:20},buttonStyle:{width: "100%",height: 40,borderRadius: 5,justifyContent: "center",alignItems: "center",backgroundColor: "white",marginTop:20},buttonTextStyle:{width:"100%",height:"100%",textAlign:"center",marginTop:10,fontSize:18},
})
const mapDispatchToProps = (dispatch) =>{return{reduxSaveEmployeeDetail:(employeDetails) => dispatch(saveEmployeeDetails(employeDetails))}}export default connect(null,mapDispatchToProps)(EmployeeDetails);

14. Now we will show, how we have to take data from redux & show them on our view.

Create ShowEmployeeDetail.js file:

import React from "react";import {View, Text,SafeAreaView,StyleSheet} from "react-native";import {connect} from "react-redux";class ShowEmployeeDetail extends React.Component{render(){return(<SafeAreaView style={styles.container}><Text style={styles.mainTextStyle}>Show Employee Details </Text><View style={styles.textViewStyle}><Text style={styles.textStyle}>Name:   </Text><Text style={styles.textStyle}> // Show Entered Name</Text></View><View style={styles.textViewStyle}><Text style={styles.textStyle}>School Name:    </Text><Text style={styles.textStyle}>// Show Entered School Name</Text></View><View style={styles.textViewStyle}><Text style={styles.textStyle}>Company Name:   </Text><Text style={styles.textStyle}>// Show Entered Company Name</Text></View></SafeAreaView>)}}const styles = StyleSheet.create({container: {flex: 1,width: "100%",height:"100%",justifyContent: 'flex-start',alignItems: 'flex-start',backgroundColor:"lightgray",},textViewStyle:{flexDirection:"row",paddingBottom:20,marginHorizontal:20},textStyle:{height:20,textAlign:"left",marginTop:10,fontSize:15},mainTextStyle:{width:"100%",height:40,textAlign:"center",marginTop:10,marginBottom:10,fontSize:20},})export default ShowEmployeeDetail

15. To show data from Redux, we need mapStateToProps and add this to connect function.

const mapStateToProps = (state) => {return{employeeDetails: state.employeeDetailReducer.employeeDetails}}

16. Now using employeeDetails we will show all data which we entered in EmployeeDeatils.js file.

Now ShowEmployeeDetail.js file looks like:

import React from "react";import {View, Text,SafeAreaView,StyleSheet} from "react-native";import {connect} from "react-redux";class ShowEmployeeDetail extends React.Component{render(){return(<SafeAreaView style={styles.container}><Text style={styles.mainTextStyle}>Show Employee Details </Text><View style={styles.textViewStyle}><Text style={styles.textStyle}>Name:   </Text><Text style={styles.textStyle}>{this.props.employeeDetails.name}</Text></View><View style={styles.textViewStyle}><Text style={styles.textStyle}>School Name:    </Text><Text style={styles.textStyle}>{this.props.employeeDetails.schoolName}</Text></View><View style={styles.textViewStyle}><Text style={styles.textStyle}>Company Name:   </Text><Text style={styles.textStyle}>{this.props.employeeDetails.companyName}</Text></View></SafeAreaView>
)
}}const styles = StyleSheet.create({container: {flex: 1,width: "100%",height:"100%",justifyContent: 'flex-start',alignItems: 'flex-start',backgroundColor:"lightgray",},textViewStyle:{flexDirection:"row",paddingBottom:20,marginHorizontal:20},textStyle:{height:20,textAlign:"left",marginTop:10,fontSize:15},mainTextStyle:{width:"100%",height:40,textAlign:"center",marginTop:10,marginBottom:10,fontSize:20},})const mapStateToProps = (state) => {return{
employeeDetails: state.employeeDetailReducer.employeeDetails
}}
export default connect(mapStateToProps,null)(ShowEmployeeDetail)

In debugger, you can see prev state, action & next state with updated values.

Recommended References-

I hope you enjoyed Redux’s use in React Native, and I look forward to seeing how you use Redux in your application for state management. If you have any questions or comments, please write a note below! You can also download this ReduxExample from gitHub.

Please share and give some claps so others can also find it useful 👏👏👏👏👏👏 !!!!

Follow me on: Facebook | Twitter | GitHub | LinkedIn

Stay connected to Codewave for more such insights and feel free to reach us at hello@codewave.in. Thanks for taking out time to read this article. We hope it enriched your existing knowledge. Do let us know your views, by sending an email to hello@codewave.in.

Codewave’s team of Design thinking led Agile, Digital transformation practitioners & lead consultants, through digital strategy consulting, design innovation and technology development, have impacted 200+ businesses in 15+ countries, since 2013.

We exploit modern open source technologies & frameworks to bring innovative solutions to life. We architect solutions keeping in mind — modularization and simplification of complex enterprise operations.

Learn how we build integrated systems & applications ⟶

--

--

Neha Sharma
codewave technologies

Sr. iOS Developer & Free Time Blogger. I am both driven and self-motivated and constantly experimenting with new technologies and techniques.