The Role Of Redux In React Native App Development

The Role Of Redux In React Native App Development

There must be times when you encountered a large number of components to manage the state internally in your React Native application. 

Components that internally handle state are used to create React Native apps. The built-in state management of React Native app development is effective for apps with few components and no plans to grow in the future. Sharing state among components becomes complicated for applications with many components or for those with the potential to grow in the future.

To address this problem, state management frameworks like Redux exist. Redux gives an application’s state a central location where any component may access the values kept there. In Redux language, the “central location” is referred to as a store.

In this post, we’ll look at leveraging Redux to handle the state in a React Native application. This piece addresses:

  • Asynchronous activities and action kinds
  • Establishing a reducer
  • Setting up a Redux store
  • Dispatching actions inside a React Native component using React Hooks

Let’s build an example app that retrieves a list of movie items from The Movie Database in order to better comprehend these ideas (TMDB API). This project’s source code is accessible at this GitHub repository. Each movie in the list can be marked as a favorite by the app user, who can then view it from a different screen by storing it in the application’s state.

Prerequisites

Make sure you have the following installed on a local environment before you start:

  • Installed Node.js version >= 14.x.x
  • TMDB account, access to API key,
  • A package manager such as npm, yarn, or npx
  • react-native-cli installed (or use npx)

Get the API key by navigating to Settings > API section after logging into your TMDB account and looking for it under the section API Key (v3 auth).

We’ll use an iOS simulator to show this. The code snippets presented in this post will function the same on an Android device or an emulator.

Using Redux with React Native 

1. Let’s get started 

Use the React Native CLI to enter the project directory to begin building a new React Native project. To develop a bottom tab navigator, we’ll first install necessary dependencies, such as react-native-vector-icons and react-navigation/bottom-tabs, and then we’ll build a Redux store.

See the official documentation for installation instructions for the React Navigation library. Throughout time, these dependencies could shift.

These directions will help you configure react-native-vector-icons.

After installing these, use a terminal window and issue the following commands:

Installing the pods will allow you to finish connecting these external libraries using CocoaPods if you’re developing for iOS:

2. Create tabs and a tab navigator 

We’ll make a tab navigator that will appear at the bottom of the screen after the installation procedure. A list of movies will be shown on the first tab utilizing information gathered from the TMDB API endpoint. A list of the movies that the app user has marked as favorites will appear in the second option.

We’ll begin by making two practice screens. Make two new files in a new directory named screens/, as follows:

  • Favorites.js
  • Movies.js

Each file should have the matching code snippet added:

 

Then, make a directory named navigation and a new file inside of it called RootNavigator.js. To add a bottom tab, use the piece of code below:

To render the RootNavigator, edit the App.js file:

3. Build the application

We’ll create the programme and execute it on an iOS simulator after this setup is finished. Use the npx react-native run-ios command to create the iOS version of the app. Execute the command npx react-native run-android to run it on an Android emulator.

The output on an iOS simulator is displayed as follows:

Image reference

 

4. Integrate an action to capture data

In Redux, an action is a payload of data that is sent from the application to the store and causes an event to occur. The state of the application can be said to have changed when anything occurs that is directly relevant to that state.

Redux uses a JavaScript object that may be considered a read-only object to describe the state. There is only one way to change it: by acting.

Getting the data from the API is the first step in creating the sample app. The application’s state is then updated with this information, and a component screen may utilize it to show a list of movies.

An item with these two qualities is the building block of an action:

  • A simple string describing the kind of activity you wish to start. For instance, the kind of action here is GET MOVIES if you wish to retrieve every movie item.
  • A data or information-containing payload

Create a new file named actions.js and a new directory called redux at the beginning. Include the next action type:

In order to keep the code sample above manageable, an action type is declared using a const variable. Several actions may be taken in the real world to cause distinct Redux application events.

Making an HTTP request to retrieve data from an API endpoint is the responsibility of the action type GET MOVIES. By specifying an action creator, this is accomplished. This is the name for a function in Redux that produces an action object.

A BASE URL and an API KEY make up an HTTP request. Let’s retrieve the list of well-liked movies for the sample app. Create a BASE URL by adding the following code and replacing API KEY with the key from your account.

Let’s employ Axios to retrieve the data from the API. It offers an API that includes HTTP request methods like get and put. At the start of the program, import the Axios, and then specify the getMovies action creator.

5. Add a movies reducer 

The application’s state cannot be updated by actions alone. A pure function known as a reducer responds to state changes by computing the updated state of the app depending on the original or current state. Reducers are pure functions, thus if the state doesn’t change, they always output the same result.

The current state and action are the two inputs given to the reducer. The reducer function’s general syntax is as follows:

Create a new file with the name reducers.js. Add the GET MOVIES action from the actions.js file. Create an initial state object by defining it with two empty arrays.  Create an initial state object by defining it with two empty arrays. The things that were favorited by the app user are stored in the second array, while the first array displays the movie items that were obtained from the API endpoint.

The moviesReducer function should then be defined with the arguments initialState and action. It switches between several action kinds using a switch statement. Each action type has a unique case that defines it. There is only one action type available for now, and that is to retrieve a list of movies. The default case returns the present state if the state doesn’t change.

6. Create a store 

A store is an object that keeps the state of the application globally rather than in individual components. The rootReducer is the first argument of a function called createStore that defines it.

An object comprising all reducers is a rootReducer. There may be more than one reducer in an app whose state is controlled by Redux. CombineReducers is a unique method provided by the Redux package that combines all reducers into a single object.

Configuring the redux-thunk library, which provides access to the thunk middleware, is crucial for building a store. It permits an asynchronous AJAX call to be made by a Redux store, such as retrieving data from an API endpoint. Each action that is dispatched using Redux is by default synchronous in nature.

CreateStore receives a middleware function as its second argument. Redux has a method called applyMiddleware that may be used to utilize middleware. This function receives arguments from every middleware function.

Copy the following code snippet into a new file called store.js:

Include this store in the App.js file to utilize it to control the state of the React Native application. Including the Provider component from the react-redux library in your imports. It passes the store to the remainder of the React Native app development while wrapping the app’s main component.

Now, the state of the application may be accessed by any React Native component that is a member of the RootNavigator.

7. Showcase a list of movies

Let’s display a list of movies that were retrieved from the API endpoint inside the Movies.js screen component.

Import the following statements first:

The useSelector hook from Redux is used in the code snippet above to get the movies array from the app’s global state.

Similar to the earlier style, this parameter is supplied within the connect() HOC and is called mapStateToProps. With the new syntax, you may use a selection function to extract data from the Redux state.

To obtain movie-related objects from the Redux store, dispatch the action getMovies using the useDispatch hook. Change the Movies element as follows:

We’ll use the FlatList component from React Native to render the movie elements. The renderItem prop is used to show each movie item from the array, and it accepts the movies array as the value of the data argument.

Each movie item includes a poster picture that is presented using an Image component as well as some metadata, such as the title of the film and the number of votes it has received. It is possible to construct a “add to favorite” button by using the TouchableOpacity component. Next, we will write logic to display the movies on the “Favorites” page and to change the status of the movie reducer.

After this step, you will receive the following output:

Image reference

8. Build actions to integrate and remove favorites 

We’ll add two additional action kinds and their authors to the actions.js file. An app user can add or remove a movie from their favorites list using one of these action kinds.

For each of the aforementioned action kinds, specify the action creators next.

To access the favorites state, modify the moviesReducer in the reducers.js file.

Send the below commands to add or delete a selection from your list of favorites. The favorites array in the state serves as a representation of this favorites list:

To access the favourites state, modify the following line:

Send the below commands to add or delete a selection from your list of favorites. The favorites array in the state serves as a representation of this favorites list:

To dynamically alter the UI based on the aforementioned triggered activities, let’s develop another handler function. This function will determine whether a movie item is included in the favorites array and, if so, whether to update the user interface (UI). We want to replace the outline that appears when a user adds anything to their favorite list with a solid favorite button.

 

Modify the TouchableOpacity button: 

9. Display favorites 

The Favorites tab will also show any movie item that is added to the list of favourites. Open the Favorites.js file in order to accomplish this, and then begin by importing the following statements:

Let’s retrieve the favorites array from the state using the useSelector hook as the Favorites screen will only display the list of things that are added.

making use of

The action to delete an item from the list will be started by the dispatch hook. An item is no longer displayed on this screen after being deleted from the favorites list.

We can provide a placeholder message if there are no items to display, or, to put it another way if the favorites array from the state is empty.

Integrate the following code snippet to the Favorites element:

The Movies screen’s UI elements are the same. After this stage, the following is the result:

Image reference

Over to you

When employing several components, using Redux’s store method to save all of your application’s information in a global object may cause performance problems. 

Yet, in the realm of React Native, there isn’t a single answer to all of these issues. It boils down to whether parts of the app’s state should be shared throughout components and which components should remain local. State in a function component is easy to comprehend and utilize when Redux is used with hooks.

DianApps is a React Native app development company that provides an extensive monitoring tool that enables you to prioritize defects, quickly recreate issues, and analyze performance in your React Native applications.

By displaying precisely how people are interacting with your app, our React Native app developers also assist you in boosting conversion rates and product utilization.

Start to proactively monitor your React Native apps with us today!

The official documentation for advanced Redux can be found here.


3


Comments (3)

Leave a Reply

Your email address will not be published. Required fields are marked *