For enquiries call:

Phone

+1-469-442-0620

HomeBlogWeb DevelopmentRedux in a React Native App Tutorial with Examples

Redux in a React Native App Tutorial with Examples

Published
25th Apr, 2024
Views
view count loader
Read it in
9 Mins
In this article
    Redux in a React Native App Tutorial with Examples

    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 and how to implement it in React Native apps in this blog.  You can further explore by enrolling in Full Stack Developer Bootcamp online. 

    What is Redux?

    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 it 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. This means if any change in the state is necessary, then the change required will only be dispatched through the actions.

    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. As pure functions, they do not change the data in the object passed to them or perform any side effects in the application. Given the same object, they should always produce the same result.

    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. Middleware helps you with error reporting, making asynchronous requests, logging, and a whole lot more.

    As we have understood the basics of redux, let's test it by implementing redux for react native application. You can become a professional.

    Advantages of Using Redux In React Native

    Some of the main advantages of using Redux in react native are:

    1. 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.
    2. 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.
    3. 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.
    4. 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.

    Not sure where to begin your web development journey? Check out Web Designing Online course online.   

    Implementing Redux in React Native Application

    Prerequisites

    • 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.

    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.

    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.

    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.

    Installing the Necessary Packages for Redux

    Open your terminal and install the following packages

    $  npm install redux
    $  npm install react-redux

    React-redux is the official binding for redux, it helps communicate with redux.

    Let's 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.

    Let's Connect the 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.

    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. 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.

    Frequently Asked Questions (FAQs)

    1Can Redux be used with React Native?

    Yes, definitely redux can be used with React Native.

    2How do you get data from Redux in React Native?

    With the help of the UseSelector hook we get data/state from the redux store.

    Ex: const count = useSelector((store) => store.count.count);
    3Can or should I create multiple stores?

    Yes, It is possible to create multiple distinct stores in an application but it is recommended to use a single store if possible.

    4Can I import my store directly, and use it in components myself?

    Yes, but it is not recommended to import stores directly. You can use the UseSelector hook from redux to access any state in-store from any of your components.

    5Is there always a one-to-one mapping between reducers and actions?

    No, As Redux docs suggest writing independent small reducer functions that are each responsible for updates to a specific slice of the state. Because actions could be handled by all, some, or none of them. As a result, components are decoupled from the actual changes to data, as one action can affect different parts of the state tree, and the component does not need to be aware of this.

    6How well does Redux “scale” in terms of performance and architecture?

    The work done by Redux generally falls into a few areas: processing actions in middleware and reducers (including object duplication for immutable updates), notifying subscribers after actions are dispatched, and updating UI components based on state changes. In fact, React-Redux in particular is heavily optimized to cut down on unnecessary re-renders, and React-Redux v5 shows noticeable improvements over earlier versions.

    Profile

    Sachin Bhatnagar

    Blog Author

    Sachin Bhatnagar is an experienced education professional with 20+ years of expertise in Media & Entertainment and Web Technologies. Currently, as the Program Director - Full-Stack at KnowledgeHut, he excels in curriculum development, hands-on training, and strategic deployment of industry-centric educational programs. His online training programs on have attracted over 25,000 learners since 2014. He actively contributes to the development of full-stack training products, leveraging KnowledgeHut's advanced learning platform. Collaborating with organizational leaders, he ensures the success of these programs and has created several technology programs prominently featured in KnowledgeHut's course offerings.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon