Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How To Use refs in React With TypeScript?
Next article icon

How to use Redux with ReactNative?

Last Updated : 02 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

First, we create a fresh ReactNative Project by running the command “npx react-native init reduxDemo”. You can also integrate Redux into your existing project.

Go to the project folder by “cd {rootDirectory}/reduxDemo” and install dependencies.

  1. “npm install redux” which is an official redux dependency.
  2. “npm install react-redux” which is used to connect redux to react.

Directory Structure: This is the Directory structure I am using. You can create your own Directory structure which suits you best.

MyAssets directory contains a Redux Directory which contains all of Redux code and a Screen directory which contains all the screen components.

I am using Burger(food) as an example to show actions such as buying or creating a Burger which will result in a Decrease or Increase in the number of Burgers.

We will create all the files in MyAssets directory one-by-one.

Directory Structure

Example Step by Step: We will create MyAssests Directory inside our reduxDemo project. MyAssets will contain all the files for the app screen component as well as for Redux. Inside MyAssets we will create a Directory named Redux which will contain all of our Redux code.

Creating Actions: Inside Redux directory we will create a directory named Burger which will contain all of our actions and reducer for the Burger.

For creating actions we will create two files bugerActionTypes.js and burgerAction.js inside the Burger directory.

  • burgerActionTypes.js: In this file, we export all the string action_type property. This file is completely optional to create and without it we will have to manually write the string Action_type in action and reducer.
JavaScript
// all action String Type will be exported from here export const INCREASE_BURGER='INCREASE_BURGER'; export const DECREASE_BURGER='DECREASE_BURGER'; 
  • burgerAction.js: In this, we will create our action function which returns action_type and optional payload property to reducer.
JavaScript
import {INCREASE_BURGER,DECREASE_BURGER} from './burgerActionTypes';   // Action functions which return action type and  // optional payLoad to burgerReducer  export const increaseBurgerAction=(parameter)=>{     return{         type:INCREASE_BURGER,         payload:parameter     } }  export const decreaseBurgerAction=()=>{     return{         type:DECREASE_BURGER     } } 

Creating Reducer: Inside Burger directory, we will create a file burgerReducer.js.In this file, we will create a burgerReducer() function which takes an initial state and action as a parameter and returns a new state of the store based on the action_type.

JavaScript
import {INCREASE_BURGER,DECREASE_BURGER} from './burgerActionTypes';  //initializing state  const initialState={     numberOfBurger:10 }  const burgerReducer=(state=initialState,action)=>{     switch(action.type){         case INCREASE_BURGER:return{             ...state,             numberOfBurger:state.numberOfBurger+action.payload         }         case DECREASE_BURGER:return{             ...state,             numberOfBurger:state.numberOfBurger-1         }         default:return state     } }  export default burgerReducer; 

Creating Store: Inside our Redux directory, we will create two files store.js and index.js.

  • Index.js: This file will be used to export all actions from a single file. This file is completely optional to create and you can import action from their respective JavaScript files also.
JavaScript
// Single file for exporting all actions export {increaseBurgerAction} from './Burger/burgerAction'; export {decreaseBurgerAction} from './Burger/burgerAction'; 
  • store.js: In this file, we will import all the reducers and then create a store and export it to App.js.We can also create a store in App.js also but to keep the code cleaner I have created a separate file.
JavaScript
import {createStore} from 'redux';  import burgerReducer from './Burger/burgerReducer';  // Passing burgerReducer to createStore const store=createStore(burgerReducer);  export default store; 
  • App.js: In App.js we import Provider component from ‘react-redux’ and store from store.js. Provider is used to pass store state to all its child components.
JavaScript
import React from 'react'; import {Provider} from 'react-redux';  import store from './MyAssets/Redux/store'; import Screen from './MyAssets/Screens/screen'    const App= () => {   return (     <Provider store={store}>     <Screen/>     </Provider>   ); };     export default App; 

Creating our Screen Component: Now finally we will create our screen component to use and update the store state. Inside MyAssets directory we will create a directory named Screens which will contain all of our app screen components. Inside Screens directory we will create a file named screen.js.

JavaScript
import React, { Component } from 'react' import { Text, View,Button } from 'react-native' import {connect} from 'react-redux' import {increaseBurgerAction,decreaseBurgerAction}  from '../Redux/index'  class Screen extends Component {     render() {         return (             <View style={{justifyContent:'center',alignItems:'center'}}>                 <View style={{marginVertical:50}}>                 <Text> Number Of Burger = {this.props.numberOfBurger} </Text>                 <Button title="Increase Burger" onPress={()=>{this.props.increaseBurger(5)}}/>                 </View>                 <View style={{marginVertical:50}}>                 <Button title="Decrease Burger" onPress={()=>{this.props.decreaseBurger()}}/>                 </View>             </View>         )     } }  const mapStateToProps=(state)=>{     return{         numberOfBurger:state.numberOfBurger     } }  const mapDispatchToProps=(dispatch)=>{         return{             increaseBurger:(parameter)=>{dispatch(increaseBurgerAction(parameter))},             decreaseBurger:()=>{dispatch(decreaseBurgerAction())}         } }  export default connect(mapStateToProps,mapDispatchToProps)(Screen); 
  • Render: This is called when the state of the store changes.
  • mapStateToProps: This function maps the store state to the screen component to be used as props. We can also rename this other than mapStateToProps.
  • mapDispatchToProps: This function maps the actions to the screen component to be called using props. We can also rename this other than mapDispatchToProps.
  • connect: This is a ‘react-redux’ inbuilt function used to connect screen component to mapStateToProps and mapDispatchToProps.Always pass mapStateToProps as a first parameter and mapDispatchToProps as the second parameter to connect() function otherwise it will generate an error.

Output:

  1. First we call this.props.increaseBurger(5) in Button from our component.Notice how we pass number ‘5’ as an parameter ,this parameter will be supplied to increaseBurgerAction(parameter) function of mapDispatchToProps function.
  2. Then the increaseBurgerAction() of burgerActions.js file will be called which will return action_type and ‘5’ as a payload to reducer function.
  3. Then the burgerReducer() function will be called which will accept an initial state and action as a parameter and then increase the numberOfBurger from the initial value to +5.
  • this.props.decreaseBurger() in Button works the same as this.props.increaseBurger(). Notice we haven’t passed any parameter this time.

Multiple Reducers: In most cases, we have to use multiple reducers in order to separate states and actions. To demonstrate this I have created another Directory named Pizza which contains code for pizzaReducer.js, pizzaActionsType.js, and pizzaActions.js.

  • store.js: In this, we use combineReducers() which is an inbuilt function of ‘redux’ to combine our reducers.
JavaScript
import {createStore,combineReducers} from 'redux';  import burgerReducer from './Burger/burgerReducer'; import pizzaReducer from './Pizza/pizzareducer';  // Combining burgerReducer and pizzaReducer in rootReducer const rootReducer=combineReducers({     burgerReducer:burgerReducer,     pizzaReducer:pizzaReducer })  // Passing rootReducer to createStore const store=createStore(rootReducer);  export default store; 
  • pizzaReducer.js:
JavaScript
import {PIZZA_DECREASE,PIZZA_INCREASE} from './pizzaActionsType';  // Initializing state  const initialState={     numberOfPizza:30 }  const pizzaReducer=(state=initialState,action)=>{     switch(action.type){         case PIZZA_INCREASE:return{             ...state,             numberOfPizza:state.numberOfPizza+action.payload         }         case PIZZA_DECREASE:return{             ...state,             numberOfPizza:state.numberOfPizza-1         }         default:return state     } }  export default pizzaReducer; 
  • pizzaActionType.js:
JavaScript
export const PIZZA_INCREASE='PIZZA_INCREASE'; export const PIZZA_DECREASE='PIZZA_DECREASE'; 
  • pizzaActions.js:
JavaScript
import {PIZZA_INCREASE,PIZZA_DECREASE} from './pizzaActionsType';   // Action functions which return action type  // and optional payLoad to burgerReducer  export const increasePizzaAction=(parameter)=>{     return{         type:PIZZA_INCREASE,         payload:parameter     } }  export const decreasePizzaAction=()=>{     return{         type:PIZZA_DECREASE     } } 
  • index.js:
JavaScript
// Single file for exporting all actions export {increaseBurgerAction} from './Burger/burgerAction'; export {decreaseBurgerAction} from './Burger/burgerAction';  export {increasePizzaAction} from './Pizza/pizzaActions'; export {decreasePizzaAction} from './Pizza/pizzaActions'; 
  • screen.js – Modifying our screen component code to use pizza actions and state.
JavaScript
import React, { Component } from 'react' import { Text, View,Button } from 'react-native' import {connect} from 'react-redux' import {increaseBurgerAction,decreaseBurgerAction,increasePizzaAction,decreasePizzaAction}  from '../Redux/index'  class Screen extends Component {     render() {         return (             <View style={{justifyContent:'center',alignItems:'center'}}>                 <View style={{marginVertical:50}}>                 <Text> Number Of Burger = {this.props.numberOfBurger} </Text>                 <Button title="Increase Burger" onPress={()=>{this.props.increaseBurger(5)}}/>                 <Button title="Decrease Burger" onPress={()=>{this.props.decreaseBurger()}}/>                 </View>                 <View style={{marginVertical:50}}>                 <Text> Number Of Pizza = {this.props.numberOfPizza} </Text>                 <Button title="Increase Burger" onPress={()=>{this.props.increasePizza(5)}}/>                 <Button title="Decrease Burger" onPress={()=>{this.props.decreasePizza()}}/>                 </View>             </View>         )     } }  const mapStateToProps=(state)=>{     return{         numberOfBurger:state.burgerReducer.numberOfBurger,         numberOfPizza:state.pizzaReducer.numberOfPizza     } }  const mapDispatchToProps=(dispatch)=>{         return{             increaseBurger:(parameter)=>{dispatch(increaseBurgerAction(parameter))},             decreaseBurger:()=>{dispatch(decreaseBurgerAction())},              increasePizza:(parameter)=>{dispatch(increasePizzaAction(parameter))},             decreasePizza:()=>{dispatch(decreasePizzaAction())}         } }  export default connect(mapStateToProps,mapDispatchToProps)(Screen); 

Output:



Next Article
How To Use refs in React With TypeScript?

R

rahulschauhan50
Improve
Article Tags :
  • Android
  • JavaScript
  • Node.js
  • Programming Language
  • ReactJS
  • Web Technologies
  • React-Redux

Similar Reads

  • How to use React Context with React-Redux ?
    React context with React-Redux is a popular state management library for React applications. Using React context with React-Redux is a powerful way to provide the Redux store to components deep within your component tree without manually passing it down through props. PrerequisitesNode.js and NPMRea
    3 min read
  • How to Integrate WebSockets with React Redux
    Integrating WebSockets with Redux allows for real-time bidirectional communication between the client (e.g. a web browser) and the server. This enables applications to push data from the server to the client instantly, facilitating features such as real-time updates, live notifications, and chat app
    6 min read
  • How to use TypeScript with React?
    TypeScript enhances JavaScript by adding strict type definitions, making your code more robust and maintainable. ReactJS, a popular library for building user interfaces, pairs excellently with TypeScript to create clean, efficient, and scalable codebases. Combining TypeScript with React offers a pow
    3 min read
  • How React Redux Works?
    Redux is a predictable state container for JavaScript apps. It helps manage the state of an application in a consistent and predictable way. By centralizing the state, Redux makes it easier to debug and maintain applications, especially as they grow in complexity. Prerequisites NodeJSNPMReactJSWhy D
    6 min read
  • How To Use refs in React With TypeScript?
    To use refs in React with TypeScript, you can take advantage of the ref attribute to directly interact with DOM elements or child components. Refs provide a way to access the underlying DOM node or React component instance and can be especially useful when you need to manage focus, control animation
    4 min read
  • How to Create Store in React Redux ?
    React Redux is a JavaScript library that is used to create and maintain state in React Applications efficiently. Here React Redux solves the problem by creating a redux store that stores the state and provides methods to use the state inside any component directly or to manipulate the state in a def
    4 min read
  • How to redirect in React with Typescript ?
    Navigating users seamlessly through a React application is a fundamental aspect of creating a smooth and intuitive user experience. In this article, we delve into the world of redirects in React, specifically addressing the use of TypeScript for enhanced type safety and developer productivity. Prere
    2 min read
  • Getting Started with Redux
    Redux is a popular state management library for JavaScript applications. It provides a way to centralize the state of an application in a single store, making it easier to debug, test, and reason about the state changes in the application. It helps to manage complex application states, making it eas
    4 min read
  • How to set initial state in Redux ?
    Redux is the tool for the management of the state throughout the whole application globally. We can set initial states in redux as a store that can only be modified with the help of the actions. But, this state must be specified somewhere first to use it.  PrerequisitesReact JSReduxApproachWe prefer
    4 min read
  • Why was Redux Toolkit created?
    Redux Toolkit was created to improve the overall development experience and to simplify the setup of the redux store and state management tasks. Redux Toolkit is also known as RTK in short. In this article, we'll discuss the problems that developers face while using Redux and how Redux Toolkit comes
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences