Redux is a standalone state management library, which can be used with any library or framework whether it’s React, React Native or any other view library. If you have developed a front-end application with React you may have used the Redux library for state management. Simple state management as parent-child becomes difficult using ‘props’ when you have to build a large and complex application because there are multiple components trying to communicate with multiple other components.
In such cases, Redux comes in handy because 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 very easily whether they are siblings or parent-child. We are going to take a look at redux with react native, how to implement react redux in React Native apps and how to install necessary packages for redux on react native in this blog. You can further explore by enrolling in a React Native Course.
What is Redux in React Native? With Example
Redux is a lightweight (2KB including dependencies) predictable state container designed to help you write JavaScript apps that behave consistently across client, server, and native environments and are easy to test. To understand redux in react native better, we can break it down into the following parts:
- Actions are plain JavaScript objects sent using the react native dispatch() method. These actions must have a type property to indicate the type of action to be carried out. They are the only source of information for the store.
Let's take an example of user login
//Action Creator
const setUser = (user) => {
return {
type: "LOGIN",
payload: {
username : user.name,
password : user.password
}
}
}
- React Native Reducers are pure functions that specify how the application’s state changes in response to the action. They take action with payload as an argument and return a new state based on the action passed to it.
Let's create reducer for our previous user action for user login.
//Reducer
const initialState = {
username: '',
password: ''
};
const loggeduser = (state = initialState, action) => {
switch (action.type) {
case "LOGIN":
return {
username : action.payload.username,
password : action.payload.password
};
default:
return state;
}
};
- Store holds the entire state of the application state as a plain javascript object. The store is created with the help of reducers, It is highly recommended to keep only one store in any Redux application.
Let’s create a store using our previous reducer for user login.
//store
const store = createStore(loggeduser);
Middlewares allow you to add extra functionality to Redux by intercepting each action sent to the reducer, so you can modify the action or cancel it, if necessary.
As we have understood the basics of redux, let's test it by implementing redux for react native application. You can become a professional.
Not sure where to begin your web development journey? Check out Web Designing Online course online.
How to Implement Redux in React Native Application?
Let's discuss in detail about how to implement and use Redux in your React Native app effortlessly and efficiently in step-by-step:
Prerequisites to Implement Redux with React Native
Here are the Prerequisites for using Redux in Your React Native App:
- Nodejs
- React-native-CLI or expo-CLI
- Basic knowledge of React Native
We are going to follow these simple steps to build a counter application.
Step 1: Create a Basic React Native app
If you are more familiar with react-native-cli, then you can use the following command to build a blank app, open your terminal and run the following command
$ react-native init nameofyourapp
OR using expo-cli
$ expo init nameofyourapp
After successfully completing this, you will get the blank app with minimal code.
Step 2: Running app on the device
To run the app on your device, run the following command on your terminal.
To run the Android app using react-native-cli, you should start the emulator first, either via Android Studio or ADB, then
$ react-native run-android
To run Android app using expo-cli, you should first install the expo-go app from Play Store, then
$ expo start
After that, you will see a QR code in the terminal, scan it using the expo-go app.
Let’s also take a look at the basic folder structure that we are going to follow.
Step 3: Let’s add the Counter Feature to the App
Open the text editor of your choice and create Home.js file inside the screens folder and write the following code in it. But before that, make following changes to App.js
//App.js
import Home from './src/screens/Home';
export default function App() {
return <Home />;
}
// screens/Home.js
import React, { useState } from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
export default function Home() {
const [counter, setCounter] = useState(0);
const handleIncreament = () => {
setCounter(counter + 1);
};
const handleDecreament = () => {
setCounter(counter - 1);
};
return (
<View style={styles.container}>
<Text style={styles.title_text}>Counter App</Text>
<Text style={styles.counter_text}>{counter}</Text>
<TouchableOpacity onPress={handleIncreament} style={styles.btn}>
<Text style={styles.btn_text}> Increment </Text>
</TouchableOpacity>
<TouchableOpacity
onPress={handleDecreament}
style={{ ...styles.btn, backgroundColor: '#6e3b3b' }}>
<Text style={styles.btn_text}> Decrement </Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
flexDirection: 'column',
padding: 50,
},
title_text: {
fontSize: 40,
fontWeight: '900',
marginBottom: 55,
},
counter_text: {
fontSize: 35,
fontWeight: '900',
margin: 15,
},
btn: {
backgroundColor: '#086972',
padding: 10,
margin: 10,
borderRadius: 10,
},
btn_text: {
fontSize: 23,
color: '#fff',
},
});
After making changes save them and reload the app, and you will see this on screen.
Untill now, it is a simple app that increases and decreases the count of clicking. In the next step, we are going to add redux to it.
How to Install the Necessary Packages for Redux in React Native?
Open your terminal and install the following packages for redux on react native:
$ npm install redux
$ npm install react-redux
React-redux is the official binding for redux, it helps communicate with redux.
1. Create Reducers and Actions and Store Them for Our Application
Create a countAction.js file inside the redux/actions folder and write the following code in it.
// redux/actions/countAction.js
export const increment = () => {
return {
type: 'COUNT_INCRESE',
};
};
export const decrement = () => {
return {
type: 'COUNT_DECRESE',
};
};
It's good practice to write action types inside another file as constants but here we only have a single action type so instead we have written it inside action.
Now Create a countReducer.js file inside the redux/reducers folder and write the following code in it.
// redux/reducers/countReducer.js
const initialState = {
count: 0,
};
export default (state = initialState, action) => {
switch (action.type) {
case 'COUNT_INCRESE':
return {
...state,
count: state.count + 1,
};
case 'COUNT_DECRESE':
return {
...state,
count: state.count - 1,
};
default:
return state;
}
};
This is the countReducer that updates app state based on action dispatched. Here we have given our app count as 0 for starting so whenever the app opens it will show the count as 0.
Next, we have to create a store with the help of reducers that is going to hold the state of our application in this case ‘count’.
So let's Create a store.js file inside the redux folder and write the following code in it.
import { createStore, combineReducers} from 'redux';
import CountReducer from './reducers/countReducer';
const rootReducer = combineReducers({
count: CountReducer,
});
export const store = createStore(rootReducer);
Here we can use thunk as middleware if we need to communicate with API and wait for its response because the actions in redux are dispatched synchronously, which is a problem for any app that needs to communicate with an external API or perform side effects. React Native Redux allows these middlewares to sit between an action being dispatched and the action reaching the reducers.
2. Connect the Redux Store to our Application
So as of now we have created a redux store for our application now lets connect it to the app.
To connect redux store with app make following changes to App.js file
// App.js
import { Provider } from 'react-redux';
import Home from './src/screens/Home';
import { store } from './src/redux/store';
export default function App() {
return (
<Provider store={store}>
<Home />
</Provider>
);
}
We are ready with redux integration in our app now lets use its functionality inside our app.
So open Home.js file and make the following changes in it and let me show you how to access state from store and update it.
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from '../redux/actions/countAction';
export default function Home() {
const dispatch = useDispatch();
const count = useSelector((store) => store.count.count);
const handleIncrement = () => {
dispatch(increment());
};
const handleDecrement = () => {
dispatch(decrement());
};
return (
<View style={styles.container}>
<Text style={styles.title_text}>Counter App</Text>
<Text style={styles.counter_text}>{count}</Text>
<TouchableOpacity onPress={handleIncrement} style={styles.btn}>
<Text style={styles.btn_text}> Increment </Text>
</TouchableOpacity>
<TouchableOpacity
onPress={handleDecrement}
style={{ ...styles.btn, backgroundColor: '#6e3b3b' }}>
<Text style={styles.btn_text}> Decrement </Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
flexDirection: 'column',
padding: 50,
},
title_text: {
fontSize: 40,
fontWeight: '900',
marginBottom: 55,
},
counter_text: {
fontSize: 35,
fontWeight: '900',
margin: 15,
},
btn: {
backgroundColor: '#086972',
padding: 10,
margin: 10,
borderRadius: 10,
},
btn_text: {
fontSize: 23,
color: '#fff',
},
});
Here we are using hooks from redux to dispatch action and access state from store. UseDispatch() hook helps us to dispatch an action that triggers necessary changes to store and UseSelector() hook helps us to access needed state from store.
Now save change and reload your app to test it.
What is happening here?
So When we click on-increment it calls a function handleIncrement which dispatches action increment this action sends type as ‘COUNT_INCRESE’ to reducer as a result reducer updates the state accordingly and we get an updated state using useSelector in our screen HomeJS.
Advantages of Using Redux In React Native
Some of the main advantages of using Redux in react native are:
- Easy Debugging: Debugging an application is simple with Redux. It is simple to understand code problems, network errors, and other types of bugs that may arise during production by logging actions and states.
- Server-side rendering: Redux can also be used to render data on the server. We can use it to manage the app's initial render by providing the app's state to the server along with the server request response. After that, the necessary components are rendered in HTML and provided to the clients.
- Predictable state: The state of Redux is always predictable. Because reducers are pure functions, they always deliver the same result when the same state and action are supplied to them. The status is also unchangeable and unalterable. This allows for difficult jobs like limitless undo and redo to be implemented. It's also possible to switch back and forth between prior states while seeing the effects in real time.
- Maintainable: Redux has tight guidelines for how code should be arranged, making it easy for someone who knows Redux to comprehend the structure of any React Native Redux example which makes it easy to maintain.
Looking for Python coaching near me? Unlock the power of this versatile language with our unique approach. Join us today and embark on a coding journey like no other.
Conclusion
We have discussed What Redux is, its different components and How to implement Redux in React Native App, advantages of using, installation of packages and how to use redux for react native. So redux helps us in managing state in application but it does not mean you should go about adding Redux in all of your apps. There are also other ways for managing the state in our application like react-context, mobx and libraries also. However, before having a good hold on the Redux components, it will be useful to brush up your basics of application development with the KnowledgeHut React Native course.
You can consider using redux if the app state is updated frequently, the logic to update that state may be complex. The app has a medium or large-sized codebase and might be worked on by many people. You need to see how that state is being updated over time.