Bacancy Bacancy
  • Customers

      Fortune 500 Clients

      Verizon
      Verizon
      Franklin Templeton
      Franklin Templeton
      The Container Store
      The Container Store
      KPMG
      KPMG
      Academy Sports & Outdoors
      Academy Sports & Outdoors
      Shell
      Shell
      Bangkok Bank Ltd
      Bangkok Bank Ltd
      The Children's Place
      The Children's Place
      Edward Jones
      Edward Jones
      United Parcel Service
      United Parcel Service
      AdviceWorks
      AdviceWorks
      NatWest Markets
      NatWest Markets
      Bridgestone
      Bridgestone

      Technologies

      React JS VueJS Angular JS React Native Flutter Full Stack
      Ruby on Rails Node JS Golang AI & ML Data Science Java
      Python Salesforce DevOps Block Chain Mobile App Embedded & Hardware
      Explore All
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
  • what we do

      Experience

      Digital Workplace Services Product Enhancement

      Insights

      AI & Automation Data Analytics

      Innovate

      Blockchain Software Engineering Services Internet of Things (IoT) Data Science Artificial Intelligence Machine Learning

      Accelerate

      Cloud - Bacancy Combalt Digital Process Automation Open Source Microsoft Dynamics Salesforce

      Assure

      Quality Assurance IT Staff Augmentation

      Embedded & Hardware

      Product Engineering Analog Design Services FPGA Engineering Service Wireless Design Embedded Software Design

      not list

      Hardware Engineering Power Engineering IoT Hardware
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
  • who we work with

      Industries

      Banking Financial services & Insurance Startups Oil & Gas

      not list

      Healthcare Life Science Real Estate & Construction Logistics
      bacancy

      Let’s grow together Partner with us

      get quote
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
  • about us

      Culture

      Agile Mindset Bacancy Values Bacancy Culture

      About Company

      About Us Leadership Team Awards & Recognition Infrastructure

      not list

      Customer Reviews Our Locations Partnership Media Coverage

      WE ARE

      GREAT PLACE TO WORK - CERTIFIEDTM

      Building and sustaining High-Trust, High-Performance CultureTM

      Bacancy Great Place to Work
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
  • technology

      Front End

      Angular Reactjs Vue.js UI/UX

      Platforms

      MS Dynamics Salesforce

      Back End

      Ruby on Rails Node.js Golang Laravel .NET Java Python

      Mobile

      React Native Flutter Android iOS

      Cloud

      AWS DevOps

      QA

      Automation Testing Software Testing

      Embedded & Hardware

      Embedded
      bacancy

      World-class expertise,Delivered

      get quote
      Explore All
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
  • PRODUCTS

      EV Products

      Battery Management System Motor Controller AC Charger Explore All

      not list

      CCS2 Controller DC Fast Charger AC Charge Controller
      bacancy

      Let’s grow together Partner with us

      get quote
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
hire us

Bacancy

Bacancy represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Rise™.

12+

Countries where we have happy customers

1050+

Agile enabled employees

06

World wide offices

10+

Years of Experience

05

Agile Coaches

14

Certified Scrum Masters

1000+

Clients projects

1458

Happy customers

  • Customers
      Technologies
      • React JS
      • Angular JS
      • Vue JS
      • Node JS
      • AI & ML
      • Explore All
      Fortune 500 Clients
      • Verizon
      • The Container Store
      • KPMG
      • Academy Sports & Outdoors
      • Bangkok Bank Ltd
      • The Children's Place
      • Edward Jones
      • Franklin Templeton
      • AdviceWorks
      • NatWest Markets
      • Bridgestone
      • United Parcel Service
  • What we do
      Experience
      • Digital Workplace Services
      • Product Enhancement
      Insights
      • AI & Automation
      • Data Analytics
      Innovate
      • Blockchain
      • Software Engineering Services
      • Internet of Things (IoT)
      Accelerate
      • Cloud - Bacancy Combalt
      • Digital Process Automation
      • Open Source
      • Microsoft Dynamics
      • Salesforce
      • Service Experience Transformation
      Assure
      • Testing
      • Resource Augmentation
      Embedded & Hardware
      • Product Engineering
      • Analog Design Services
      • FPGA Engineering Service
      • Wireless Design
      • Embedded Software Design
      • Hardware Engineering
      • Power Engineering
      • IoT Hardware
      • AL/ML
  • who we work with
      Industries
      • Banking Financial services & Insurance
      • Startups
      • Oil & Gas
      • Healthcare Life Science
      • Real Estate & Construction
      • Logistics
  • About Us
      About Company
      • About Us
      • Leadership Team
      • Awards & Recognition
      • Infrastructure
      • Our Locations
      • Partnership
      Culture
      • Agile Mindset
      • Bacancy Values
      • Bacancy Culture
  • Technology
      Front End
      • Angular
      • Reactjs
      • Vue.js
      • UI/UX
      Platforms
      • MS Dynamics
      • Salesforce
      Back End
      • Ruby on Rails
      • Node.js
      • Golang
      • Laravel
      • .NET
      • Java
      • Python
      Mobile
      • React Native
      • Flutter
      • Android
      • iOS
      Cloud
      • AWS
      • DevOps
      QA
      • Automation Testing
      • Software Testing
      Embedded & Hardware
      • Embedded
      Explore All
  • Products
    • Battery Management System
    • Motor Controller
    • CCS2 Controller
    • AC Charger
    • DC Fast Charger
    • AC Charge Controller
    • Explore All
  • Careers
  • Work @ Bacancy
  • Blogs
  • Resources
  • Customer Reviews
  • Contact
  • Get Quote
Redux with React Hooks

How to Use Redux with React Hooks in React Native Application

Riken Solanki
Riken Solanki Content Lead
Last Updated on December 12, 2022
June 17, 2020 6 min read

The react-redux library has official support for the React Hooks as well as React Native applications to use Redux as a state management library. With more and more adoption of React Hooks and its ability to handle side effects and components, it is now regarded as a standard functional component pattern. Redux React hooks are available since the release of React version 16.8.x, and in this blog post, we will explore a structured pattern React Native Redux Hooks and how to use Redux with React Hooks.

Redux-React hooks are available since the release of React version 16.8.x, and in this blog post, we will explore a structured pattern for Redux making use of React Native.

React Hooks and Redux Hooks

To replace the higher-order component Redux hook API is used, “connect()” with hooks like “useDispatch” and “useSelector” as present React-Redux provides 3 hooks:

⦿ useSelector():

This can help you replace the mapStateToProps. The purpose is to extract the data from the ‘Redux’ store whenever function component renders.

⦿ useDispatch():

A replacement to mapDispatchToProps, it’s purpose is to return the reference to the dispatch object.

⦿useStore():

It helps to return the reference that was wrapped in Redux . It is ideal to use in specific scenarios, like replacing reducers.

Let’s Start with Installing/ How to Add Redux

"dependencies": {
 "@react-native-community/masked-view": "0.1.5",
 "expo": "~36.0.0",
 "react": "~16.9.0",
 "react-dom": "~16.9.0",
 "react-native": "https://github.com/expo/react-native/archive/sdk-36.0.0.tar.gz",
 "react-native-gesture-handler": "~1.5.0",
 "react-native-paper": "3.4.0",
 "react-native-reanimated": "~1.4.0",
 "react-native-safe-area-context": "0.6.0",
 "react-native-screens": "2.0.0-alpha.12",
 "react-navigation": "4.0.10",
 "react-navigation-stack": "2.0.10",
 "react-redux": "7.1.3",
 "redux": "4.0.5"
 },

Source: Heartbeat

The very next step is to install the dependencies to use Redux and manage the state:

yarn add redux react-redux lodash.remove

Here I am going to follow ducks for directory structure to manage Redux with React Hooks files as ducks let you have modular reducers in the application itself. There is no need to create separate files for types, actions, and action creators. All of these can be managed in one modular file, and if it demands to create more than one reducer, then you can simply define multiple header reducer files.

How to Add Action Types and Creators

While using React Redux with hooks, the state is characterized by JS object. It would be best if you considered an object as ready as it does not allow you to make changes in the state. This is the reason you need to take the help of actions. Actions are similar to the events in React Hooks with Redux.

Actions are similar to the events in Redux.

To start with

src/ directory 
Create subdirectory – Redux
Create a new file - notesApp.js.
Now you have provided an additional ability to allow users to add notes. 
// Action Types
export const ADD_NOTE = 'ADD_NOTE'
export const DELETE_NOTE = 'DELETE_NOTE'

If you are looking to implement redux with React Hooks in your React Native application, Contact the best React Native App Development Company now.

Let’s Move Ahead to Add a Reducer

To Create Reducers

Path: src / store /
File: /ducks/example.js

The receiver of the action is addressed as a reducer; whenever an action takes place, the state of the application changes and the app’s state is done by reducers. Reducer functions based on the previous and initial state.

// import the dependency
import remove from 'lodash.remove'

// reducer

const initialState = []

function notesReducer(state = initialState, action) {
  switch (action.type) {
    case ADD_NOTE:
      return [
        ...state,
        {
          id: action.id,
          note: action.note
        }
      ]

    case DELETE_NOTE:
      const deletedNewArray = remove(state, obj => {
        return obj.id != action.payload
      })
      return deletedNewArray

    default:
      return state
  }
}

export default notesReducer

Source: Viblo

Redux Store

Basically, the Redux store is responsible for the following:

  • Holds application state
  • Allows access to the state via getState()
  • Let the state be updated via dispatch(action).
  • Provides permission to registers listeners via subscribe(listener)

Under the src folder, create a store.js file and configure it with the Redux store to define the initialState parameter.

 
/*
 * src/store.js
 * No initialState
*/import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/rootReducer';export default function configureStore() {
 return createStore(
  rootReducer,
   applyMiddleware(thunk)
 );
}

Source: Medium

To Create Store

The Redux store is set up, but the application has no access to it. Using a provider from React binding react-redux, the store will be available to every component in the application. Here I am going to consider the store and children as props.

 
/*
 src/index.js
*/import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import configureStore from './store';import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';ReactDOM.render(
 < Provider store={configureStore()} >
  < App />
 < /Provider >,
 document.getElementById('root')
);
registerServiceWorker();

Source: Medium

To Access the Global State

To access state with Redux useSelector it is advisable to use the mapStateToProps inside connect(). It allows you to extract data from the Redux store state using a selector function.

The significant difference between the argument and the Hook is the selector will present any value in return not any object as a result.

Simply open the ViewNotes.js file.

// ...after rest of the imports
import { useSelector } from 'react-redux'

Dispatching Actions

The Hook is only used to perform to dispatch function from the Redux store. Simply import it from the react-redux along with the action creators to dispatch an action.

import { useSelector, useDispatch } from 'react-redux'

To dispatch an action, define the following statement useSelectorHook in React Native:

const dispatch = useDispatch()

To trigger these events:

const addNote = note => dispatch(addnote(note))
const deleteNote = id => dispatch(deletenote(id))

FYI, here’s a code snipet of List.Item
< List.Item
  title={item.note.noteTitle}
  description={item.note.noteValue}
  descriptionNumberOfLines={1}
  titleStyle={styles.listTitle}
  onPress={() => deleteNote(item.id)}
/ >

To Run the Application

So far, you are good to go with running an application from the terminal window executing the command called expo start. For your reference, here’s a complete snippet of code.

// ViewNotes.js
import React from 'react'
import { StyleSheet, View, FlatList } from 'react-native'
import { Text, FAB, List } from 'react-native-paper'
import { useSelector, useDispatch } from 'react-redux'
import { addnote, deletenote } from '../redux/notesApp'

import Header from '../components/Header'

function ViewNotes({ navigation }) {
  // const [notes, setNotes] = useState([])

  // const addNote = note => {
  // note.id = notes.length + 1
  // setNotes([...notes, note])
  // }

  const notes = useSelector(state => state)
  const dispatch = useDispatch()
  const addNote = note => dispatch(addnote(note))
  const deleteNote = id => dispatch(deletenote(id))

  return (
    < >
      < Header titleText='Simple Note Taker' / >
      < View style={styles.container} >
        {notes.length === 0 ? (
          < View style={styles.titleContainer} >
            < Text style={styles.title}>You do not have any notes< /Text >
          < /View >
        ) : (
          < FlatList
            data={notes}
            renderItem={({ item }) => (
              < List.Item
                title={item.note.noteTitle}
                description={item.note.noteValue}
                descriptionNumberOfLines={1}
                titleStyle={styles.listTitle}
                onPress={() => deleteNote(item.id)}
              / >
            )}
            keyExtractor={item => item.id.toString()}
          / >
        )}
        < FAB
          style={styles.fab}
          small
          icon='plus'
          label='Add new note'
          onPress={() =>
            navigation.navigate('AddNotes', {
              addNote
            })
          }
        / >
      < /View >
    
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    paddingHorizontal: 10,
    paddingVertical: 20
  },
  titleContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    flex: 1
  },
  title: {
    fontSize: 20
  },
  fab: {
    position: 'absolute',
    margin: 20,
    right: 0,
    bottom: 10
  },
  listTitle: {
    fontSize: 20
  }
})

export default ViewNotes

Wrapping Up

The additional hooks such as useDispatch and useSelector Redux not only eliminates the need to write ample of boilerplate code but also provides the additional advantages of using functional components. To understand more in detail about how to use React Redux Hooks in React Native application, please refer to their official document. If you are planning to hire React Native developers, with the relevant skillset who can help you implement Redux Hooks in your React-Redux application, then you have landed on the right page. We are a globally renowned react native development company and can help you build visually stunning and future-proof mobile app solutions. Based upon your preference and convenience hire React native developers to get the job done.


Expand Your Digital Horizons With Us.

Start a new project or take an existing one to the next level. Get in touch to start small, scale-up, and go Agile.


Or
E-mail us : [email protected]

Your Success Is Guaranteed !

Related Articles

Animated Progress Meter in React Native
Paridhi Wadhwani
Rishi Shah

January 11, 2023

React Native

How to Develop an Animated Progress Meter in React Native?

By : Paridhi Wadhwani & Rishi Shah

Quick Summary: This blog will show you how to create a speedometer, or an animated progress meter in React Native using the interpolate function in...

5 Minute Read
Read More
React Native Architecture
Paridhi Wadhwani

November 18, 2022

React Native

Everything About The New React Native Architecture 2023 Update

By : Paridhi Wadhwani

Quick Summary: If you still haven’t got a chance to check the new React Native architecture, or as it is also called react native re...

7 Minute Read
Read More
React Native For Web
Paridhi Wadhwani

October 14, 2022

React Native

React Native For Web: A Reality Too Good To Be True!

By : Paridhi Wadhwani

Quick Summary: React Native for Web, is another sure-shot reason why use React Native, allowing programmers to utilize React Native Components and APIs on the...

10 Minute Read
Read More

india India (HQ)

Corporate House
15-16, Times Corporate Park, Thaltej, Ahmedabad, Gujarat 380059

USA USA

601 Brickell Key Drive, Suite 700, Miami, Florida, 33131, USA

canada Canada

71 Dawes Road, Brampton, On L6X 5N9, Toronto

australia-flag Australia

351A Hampstead Rd, Northfield SA 5085

UAE UAE

1608 Clover Bay, Business Bay, Dubai, UAE. PO Box 62049

sweden Sweden

Junkergatan 4, 126 53 Hagersten


Great Place to Work

Get in Touch

call-yellow-icon

Contact Number

+1 347 441 4161

gmail-icon

Email Us

[email protected]


  • Bacancy Behance
  • Bacancy Uplabs
  • Bacancy Pinterest
  • Brochure
  • Quality Assurance
  • Resources
  • Tutorials
  • Customer Reviews
  • Privacy Policy
  • FAQs
  • Contact Us
  • Sitemap
  • Employee
bacancy google review 4.6
bacancy google review
bacancy glassdoor review 4.5
bacancy glassdoor review
bacancy clutch review 4.8
bacancy clutch review
bacancy goodfirms review 4.5
bacancy goodfirms review
X

Get Our Newsletter

Be The First To Get The Latest Updates And Tutorials.

Request A Free Consultation