SlideShare a Scribd company logo
How to Use
Redux with
React Hooks in
React Native
Application
w w w . b a c a n c y t e c h n o l o g y . c o m
The react-redux library has official support
for the Hooks in React 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, now, it
is regarded as a standard functional
component pattern.
Redux 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.
Hooks for
React-Redux:
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.
"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
Let’s Start with Installing
Redux
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 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 reducer files.
How to Add Action Types and Creators
While using Redux, 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 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'
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.
Let’s Move Ahead to Add a
Reducer
// 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
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)
Basically, the Redux store is responsible
for the following:
Under the src folder, create a store.js file
and configure it with the Redux store to
define the initialState parameter.
Redux Store
/*
* 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
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.
To Create Store
/*
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 state with Redux, use the
useSelector, it is very similar to 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'
To Access the Global State
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:
const dispatch = useDispatch()
Dispatching Actions
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 trigger these events:
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.
To Run the Application
The additional hooks such as useDispatch
and useSelector 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, please refer to
their official document. If you are planning
to hire React Native developers, with the
relevant skillset who can help you
implement 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.
Wrapping Up
Thank you

More Related Content

What's hot

MVest Spring Job Execution
MVest Spring Job ExecutionMVest Spring Job Execution
MVest Spring Job Execution
Shraddha Bora
 
React with Redux
React with ReduxReact with Redux
React with Redux
Stanimir Todorov
 
React redux
React reduxReact redux
React redux
Michel Perez
 
React lecture
React lectureReact lecture
React lecture
Christoffer Noring
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
Christoffer Noring
 
Google apps script database abstraction exposed version
Google apps script database abstraction   exposed versionGoogle apps script database abstraction   exposed version
Google apps script database abstraction exposed version
Bruce McPherson
 
Advanced Akka For Architects
Advanced Akka For ArchitectsAdvanced Akka For Architects
Advanced Akka For Architects
Lightbend
 
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & Redux
Visual Engineering
 
Redux training
Redux trainingRedux training
Redux training
dasersoft
 
iOS for ERREST - alternative version
iOS for ERREST - alternative versioniOS for ERREST - alternative version
iOS for ERREST - alternative version
WO Community
 
React 101
React 101React 101
React 101
Casear Chu
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
Christoffer Noring
 
Redux "Bad" Practices - A List of 13 Bad Practices and How to Avoid Them
Redux "Bad" Practices - A List of 13 Bad Practices and How to Avoid ThemRedux "Bad" Practices - A List of 13 Bad Practices and How to Avoid Them
Redux "Bad" Practices - A List of 13 Bad Practices and How to Avoid Them
Adam Klein
 
Dbabstraction
DbabstractionDbabstraction
Dbabstraction
Bruce McPherson
 
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
Amazon Web Services
 
React & Redux
React & ReduxReact & Redux
React & Redux
Federico Bond
 
Ext J S Observable
Ext J S ObservableExt J S Observable
Ext J S Observable
jason hu 金良胡
 
Ext Js Events
Ext Js EventsExt Js Events
Ext Js Events
jason hu 金良胡
 
Google cloud datastore driver for Google Apps Script DB abstraction
Google cloud datastore driver for Google Apps Script DB abstractionGoogle cloud datastore driver for Google Apps Script DB abstraction
Google cloud datastore driver for Google Apps Script DB abstraction
Bruce McPherson
 
Client-side Rendering with AngularJS
Client-side Rendering with AngularJSClient-side Rendering with AngularJS
Client-side Rendering with AngularJS
David Lapsley
 

What's hot (20)

MVest Spring Job Execution
MVest Spring Job ExecutionMVest Spring Job Execution
MVest Spring Job Execution
 
React with Redux
React with ReduxReact with Redux
React with Redux
 
React redux
React reduxReact redux
React redux
 
React lecture
React lectureReact lecture
React lecture
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
 
Google apps script database abstraction exposed version
Google apps script database abstraction   exposed versionGoogle apps script database abstraction   exposed version
Google apps script database abstraction exposed version
 
Advanced Akka For Architects
Advanced Akka For ArchitectsAdvanced Akka For Architects
Advanced Akka For Architects
 
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & Redux
 
Redux training
Redux trainingRedux training
Redux training
 
iOS for ERREST - alternative version
iOS for ERREST - alternative versioniOS for ERREST - alternative version
iOS for ERREST - alternative version
 
React 101
React 101React 101
React 101
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Redux "Bad" Practices - A List of 13 Bad Practices and How to Avoid Them
Redux "Bad" Practices - A List of 13 Bad Practices and How to Avoid ThemRedux "Bad" Practices - A List of 13 Bad Practices and How to Avoid Them
Redux "Bad" Practices - A List of 13 Bad Practices and How to Avoid Them
 
Dbabstraction
DbabstractionDbabstraction
Dbabstraction
 
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
MBL301 Data Persistence to Amazon Dynamodb for Mobile Apps - AWS re: Invent 2012
 
React & Redux
React & ReduxReact & Redux
React & Redux
 
Ext J S Observable
Ext J S ObservableExt J S Observable
Ext J S Observable
 
Ext Js Events
Ext Js EventsExt Js Events
Ext Js Events
 
Google cloud datastore driver for Google Apps Script DB abstraction
Google cloud datastore driver for Google Apps Script DB abstractionGoogle cloud datastore driver for Google Apps Script DB abstraction
Google cloud datastore driver for Google Apps Script DB abstraction
 
Client-side Rendering with AngularJS
Client-side Rendering with AngularJSClient-side Rendering with AngularJS
Client-side Rendering with AngularJS
 

Similar to How to use redux with react hooks in react native application

React js programming concept
React js programming conceptReact js programming concept
React js programming concept
Tariqul islam
 
Getting started with Redux js
Getting started with Redux jsGetting started with Redux js
Getting started with Redux js
Citrix
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тяга
Vitebsk Miniq
 
Simple React Todo List
Simple React Todo ListSimple React Todo List
Simple React Todo List
Ritesh Chaudhari
 
React js
React jsReact js
React js
Rajesh Kolla
 
Vuex
VuexVuex
A full introductory guide to React
A full introductory guide to ReactA full introductory guide to React
A full introductory guide to React
Jean Carlo Emer
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
Remo Jansen
 
Redux and context api with react native app introduction, use cases, implemen...
Redux and context api with react native app introduction, use cases, implemen...Redux and context api with react native app introduction, use cases, implemen...
Redux and context api with react native app introduction, use cases, implemen...
Katy Slemon
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptx
BOSC Tech Labs
 
Reactive.architecture.with.Angular
Reactive.architecture.with.AngularReactive.architecture.with.Angular
Reactive.architecture.with.Angular
Evan Schultz
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
StephieJohn
 
downloads_introduction to redux.pptx
downloads_introduction to redux.pptxdownloads_introduction to redux.pptx
downloads_introduction to redux.pptx
NavneetKumar111924
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today
Nitin Tyagi
 
React outbox
React outboxReact outbox
React outbox
Angela Lehru
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
Varun Raj
 
Maintaining sanity in a large redux app
Maintaining sanity in a large redux appMaintaining sanity in a large redux app
Maintaining sanity in a large redux app
Nitish Kumar
 
Redux workshop
Redux workshopRedux workshop
Redux workshop
Imran Sayed
 
A React Journey
A React JourneyA React Journey
A React Journey
LinkMe Srl
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
Vedran Blaženka
 

Similar to How to use redux with react hooks in react native application (20)

React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
Getting started with Redux js
Getting started with Redux jsGetting started with Redux js
Getting started with Redux js
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тяга
 
Simple React Todo List
Simple React Todo ListSimple React Todo List
Simple React Todo List
 
React js
React jsReact js
React js
 
Vuex
VuexVuex
Vuex
 
A full introductory guide to React
A full introductory guide to ReactA full introductory guide to React
A full introductory guide to React
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
 
Redux and context api with react native app introduction, use cases, implemen...
Redux and context api with react native app introduction, use cases, implemen...Redux and context api with react native app introduction, use cases, implemen...
Redux and context api with react native app introduction, use cases, implemen...
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptx
 
Reactive.architecture.with.Angular
Reactive.architecture.with.AngularReactive.architecture.with.Angular
Reactive.architecture.with.Angular
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
downloads_introduction to redux.pptx
downloads_introduction to redux.pptxdownloads_introduction to redux.pptx
downloads_introduction to redux.pptx
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today
 
React outbox
React outboxReact outbox
React outbox
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
Maintaining sanity in a large redux app
Maintaining sanity in a large redux appMaintaining sanity in a large redux app
Maintaining sanity in a large redux app
 
Redux workshop
Redux workshopRedux workshop
Redux workshop
 
A React Journey
A React JourneyA React Journey
A React Journey
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
 

More from Katy Slemon

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
 

Recently uploaded

Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Pitangent Analytics & Technology Solutions Pvt. Ltd
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
Pablo Gómez Abajo
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 

Recently uploaded (20)

Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 

How to use redux with react hooks in react native application

  • 1. How to Use Redux with React Hooks in React Native Application w w w . b a c a n c y t e c h n o l o g y . c o m
  • 2. The react-redux library has official support for the Hooks in React 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, now, it is regarded as a standard functional component pattern. Redux 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.
  • 4. 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.
  • 5. "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 Let’s Start with Installing Redux
  • 6. 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 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 reducer files. How to Add Action Types and Creators
  • 7. While using Redux, 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 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'
  • 8. 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. Let’s Move Ahead to Add a Reducer
  • 9. // 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
  • 10. 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) Basically, the Redux store is responsible for the following: Under the src folder, create a store.js file and configure it with the Redux store to define the initialState parameter. Redux Store
  • 11. /* * 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
  • 12. 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. To Create Store
  • 13. /* 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
  • 14. To access state with Redux, use the useSelector, it is very similar to 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' To Access the Global State
  • 15. 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: const dispatch = useDispatch() Dispatching Actions
  • 16. 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 trigger these events:
  • 17. 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. To Run the Application
  • 18.
  • 19. The additional hooks such as useDispatch and useSelector 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, please refer to their official document. If you are planning to hire React Native developers, with the relevant skillset who can help you implement 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. Wrapping Up