How To Use Redux In React Native

HamidReza Alizadeh
7 min readNov 5, 2020

React Native Redux Example | How To Use Redux In React Native is today’s leading topic. Redux is a standalone state management library, which can be used with any library or framework. If your background is React developer, then you have used the Redux library with React.

Overview of React Native Redux Example

  • Step 1: Install React Native on mac.
  • Step 2: Add TextBox and Button.
  • Step 3: Define the state and input handler.
  • Step 4: Create actions, reducers, and components folder.
  • Step 5: Create a Reducer function.
  • Step 6: Create a Redux store.
  • Step 7: Pass the store to the React Native app.
  • Step 8: Connect React Native app to the Redux store.

React Native Redux Example Tutorial

The primary use of Redux is that we can use one application state as a global state and interact with the state from any react component is very easy, whether they are siblings or parent-child. Now, let us start the React Native Redux Example Tutorial by installing React Native on Mac first.

We start our project by installing React Native CLI globally on the Mac. You can skip the following command if you have already installed it.

#Step 1: Install React Native.

Type the following command.

npm install -g react-native-cli

Okay, now for creating a new application, type the following command.

react-native init rncreate
cd rncreate

Now, after installing, we need to open this application in the two different Simulators.

For testing on iOS simulator, type the following command.

react-native run-ios

If you have configured XCode correctly, then one iOS device will pop up as well as the development server will also start.

To open the project inside the Android Simulator, type the following command.

react-native run-android

Install the redux and react-redux library using the following command.

yarn add redux react-redux# ornpm install redux react-redux --save

#Step 2: Add Textbox and Button into the App.js.

Okay, so we will add a text box and button to add places. So let us add the TextInput and Button. Also, we will add the flexbox layout. Write the following code inside the App.js file.

// App.jsimport React, {Component} from 'react';
import { StyleSheet, View, TextInput, Button } from 'react-native';
export default class App extends Component {placeSubmitHandler = () => {
console.log("Submitted");
}
render() {
return (
<View style={ styles.container }>
<View style = { styles.inputContainer }>
<TextInput
placeholder = "Seach Places"
style = { styles.placeInput }
></TextInput>
<Button title = 'Add'
style = { styles.placeButton }
onPress = { this.placeSubmitHandler }
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
paddingTop: 30,
justifyContent: 'flex-start',
alignItems: 'center',
},
inputContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
width: '100%'
},
placeInput: {
width: '70%'
},
placeButton: {
width: '30%'
},
listContainer: {
width: '100%'
}
});

#Step 3: Define the state and input handler.

Okay, now we need a state to manage. So we define the initial state like following.

// App.jsstate = {
placeName: '',
places: []
}
placeSubmitHandler = () => {
console.log("Submitted");
}

#Step 4: Create the following folders inside Root.

Create the following folders.

  1. actions
  2. reducers
  3. components

Inside the actions folder, create one file called types.js. Add the following line inside types.js.

export const ADD_PLACE = 'ADD_PLACE'

The action type is the reducer’s operation type. Based on the action type, the reducer case will be executed, and we modify the state in such a way that it remains pure. So we create a copy of the existing state and return a new state.

Now, create one more file called place.js in the same directory.

// place.jsimport { ADD_PLACE } from './types';export const addPlace = placeName => {
return {
type: ADD_PLACE,
payload: placeName
}
}

The addPlace() function returns an action. Now, based on that action, the reducers function’s case is executed.

But, we need to connect this action to our App.js component somehow. Otherwise, we can not add the data to the Redux store. Also, we need first to create a store. But before, we also need to create a reducer function. So, first, create a reducer, then create a store and then connect the React Native application to the Redux store.

#Step 5: Create a Reducer function.

Inside reducers function, create one file called placeReducer.js. Add the following code inside it.

// placeReducer.jsimport { ADD_PLACE } from '../actions/types';const initialState = {
placeName: '',
places: []
};
const placeReducer = (state = initialState, action) => {
switch(action.type) {
case ADD_PLACE:
return {
...state,
places: state.places.concat({
key: Math.random(),
value: action.payload
})
};
default:
return state;
}
}
export default placeReducer;

So, here, we have defined the function called placeReducer that accepts the two arguments.

  1. state
  2. action

The first time, it will take the initial state of our application, and then we pass whatever argument; it takes that argument and operates based on the case execution. The second argument is action, which consists of type and payload. The payload is the place name; we have entered inside the text box. So it adds the text box’s value inside places array.

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

#Step 6: Create a Redux Store.

Inside the root folder, create one file called store.js and add the following code.

// store.jsimport { createStore, combineReducers } from 'redux';
import placeReducer from './reducers/placeReducer';
const rootReducer = combineReducers({
places: placeReducer
});
const configureStore = () => {
return createStore(rootReducer);
}
export default configureStore;

Here, we have created the redux store and passed the reducer to that store. The combineReducer function combines all the different reducers into one and forms the global state. So this is the global state of our whole application.

#Step 7: Pass the Store to the React Native app.

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

// index.jsimport { 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';const store = configureStore()const RNRedux = () => (
<Provider store = { store }>
<App />
</Provider>
)
AppRegistry.registerComponent(appName, () => RNRedux);

It is almost the same as React web application, in which we pass the Provider as a root element and pass the store, and then via react-redux’s connect() function, we can connect the any react component to redux store.

#Step 8: Connect React Native app to Redux store.

Finally, we connect our App.js component to the Redux store. For that, we need the connect() function from the react-redux library.

// App.jsimport React, { Component } from 'react';
import { StyleSheet, View, TextInput, Button, FlatList } from 'react-native';
import ListItem from './components/ListItem';
import { connect } from 'react-redux';
import { addPlace } from './actions/place';
class App extends Component { state = {
placeName: '',
places: []
}
placeSubmitHandler = () => {
if(this.state.placeName.trim() === '') {
return;
}
this.props.add(this.state.placeName);
}
placeNameChangeHandler = (value) => {
this.setState({
placeName: value
});
}
placesOutput = () => {
return (
<FlatList style = { styles.listContainer }
data = { this.props.places }
keyExtractor={(item, index) => index.toString()}
renderItem = { info => (
<ListItem
placeName={ info.item.value }
/>
)}
/>
)
}
render() {
return (
<View style={ styles.container }>
<View style = { styles.inputContainer }>
<TextInput
placeholder = "Seach Places"
style = { styles.placeInput }
value = { this.state.placeName }
onChangeText = { this.placeNameChangeHandler }
></TextInput>
<Button title = 'Add'
style = { styles.placeButton }
onPress = { this.placeSubmitHandler }
/>
</View>
<View style = { styles.listContainer }>
{ this.placesOutput() }
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
paddingTop: 30,
justifyContent: 'flex-start',
alignItems: 'center',
},
inputContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
width: '100%'
},
placeInput: {
width: '70%'
},
placeButton: {
width: '30%'
},
listContainer: {
width: '100%'
}
});
const mapStateToProps = state => {
return {
places: state.places.places
}
}
const mapDispatchToProps = dispatch => {
return {
add: (name) => {
dispatch(addPlace(name))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App)

Here, when we click the add button, we get the textbox value and then send it to the action with that value. Now that action returned the object with the action type and payload and based on the type, and the reducer will be executed and add that values inside the store.

Now, if the store’s values are changed, then we need to update the UI based on the new values. That is why the mapStateToProps function is created. So, when the store’s places array gets the new value, render function executed again, and update the UI.

The mapDispatchToProps function helps us to connect our application to the necessary action so that action then further executed by a reducer and change the application state.

Also, inside the components folder, create one file called ListItem.js and add the following code inside it.

// ListItem.jsimport React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
const ListItem = (props) => {
return (
<TouchableOpacity>
<View style = { styles.listItem }>
<Text>{ props.placeName }</Text>
</View>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
listItem: {
width: '100%',
padding: 10,
marginBottom: 10,
backgroundColor: '#eee'
}
});
export default ListItem;

This component receives the properties from the parent component and displays the data in the proper format. Save the file and go to your Simulators, and refresh the screen.

--

--