SlideShare a Scribd company logo
Redux
Effective State Management In React Applications
Author: @rc-chandan
Agenda
1. Local state vs Global state
2. Redux Architecture
3. Redux demo code (Todo console example)
a. createStore(reducer, [preloadedState], [enhancer])
b. store.subscribe(callback)
c. combineReducers({reducerKey: reducerValue, …})
4. React with Redux code example
a. react-redux
b. Provider component
c. Connect, mapStateToProps, mapDispatchToProps, Actions, reducers etc.
5. Selectors for computed state
a. reselect library for memoization of computed state
React State vs Redux State
Local state (React)
1. Good for small application where there is not a lot of components, easier to write as it is inline.
2. In complex applications, local state is preferably used for short term states which changes rapidly
and atomically and follows these conditions
a. Other part of the application does not need that piece of state.
b. We are not serializing the state as it is very minor UI level state like temporary textbox data. Applied filters
to drop down menu or tables.
c. If you want the application to resume with all these minute details then do not use inline component states.
3. Difficulties in sharing state between unrelated components.
4. There is no single source of truth.
5. Difficult to debug if the application components composition is complex.
6. There is no way to track changes to the state and going back to a previous state.
7. Serialization and deserialization of the local state is difficult.
React State vs Redux State
Global state (Redux)
1. Preferable for complex applications, as it creates a single state object for the entire application
and removes logic to manipulate state from the component classes.
2. It is easier to serialize the whole application state and resume it afterwards.
3. Redux state store is immutable so history of the store is persisted, which gives features like time
travel debugging. Also going back to previous state is easy.
4. Sharing a piece of state to different components is simple as any number of components can
subscribe to that piece of the state.
5. Concepts like selectors can be used to reuse parts of state for creating new state structure for
components if needed.
Redux Architecture
Components of Redux
Store:
1. Store contains the entire state of an application and manages it in an immutable fashion.
2. Store is created using createStore function provided by redux.
3. Store has utility functions like dispatch, subscribe, getState, replaceReducer etc.
Actions:
1. Action objects are plain JS objects with a type property can optionally have some payload also.
Dispatcher:
1. Dispatcher is a component of redux that dispatches a given action to all the reducers.
2. Dispatcher can be invoked by store.dispatch method.
Reducer:
1. Function that takes a state and an action, returns the modified state.
2. For every action dispatched by dispatcher, all the reducer are notified.
Todo list console app using only Redux
Demo
Redux in action (Todo list code)
react-redux
● JS lib created by redux team to make redux easily pass state and action creators to react
components.
● react-redux components and APIs:
○ <Provider store />
■ React component that will auto subscribe to store passed to it.
○ connect(mapStateToProps, mapDispatchToProps)(TargetComponent)
■ Enhancer function that injects state and/or action creators to react components.
○ mapStateToProps(state, ownProps):
■ Injects state object as props to the target component
○ mapDispatchToProps(dispatch):
■ Injects action creator as props to the target component
○ bindActionCreators(actionCreators, dispatch):
■ Binds dispatch with action creators that are being passed to the target component
Todo list app using React & Redux
Live app demo
Selectors
● JS functions that takes the state and/or condition, returns a computed state.
● Selectors are functions that make queries on the state object and returns the result.
● Useful for functionalities like conditional filtering, extracting a part of the state obj.
● Selectors are invoked while extracting state in mapStateToProps.
● State and props can be passed to the selector.
Visibility filter using selectors in todo list app
Selector code
Reselect
1. Selectors are useful but they are inefficient, they do the same processing repeatedly for
each related action dispatch.
2. This problem can be solved by implementing a memoization algo that remembers what
was the previous value when similar input was processed by the selector. Thus reducing
unnecessary repeated processing of the same data.
3. That is where reselect comes in, it is a memoization enabled selector lib created again by
the awesome Redux team.
4. Reselect has a cache for already processed results and when equivalent queries are fired
it returns result from the cache thus speeding up the selection process.
5. Selectors created by reselect are also chainable.
Visibility filter using reselect in todo list app
Reselect code
Redux Saga (Side effect management)
- Generator functions that listen to actions and yields new actions.
- Great for side effect management like async calls and long running computations.
- Makes react code look cleaner by moving side effects to separate file.
- 100% unit testable by mocking API responses.
E.g.
function* login(action) {
try{
const response = yield call(loginApi, action.username, action.password);
if(response.ok)
yield put(loginSuccessAction(user);
} catch (error) {
yield put(loginFailureAction(error);
}
}
// subscribe to action type
yield takeLatest(‘LOGIN_ACTION_TYPE, login);
- Redux saga provides utility functions like takeLatest, takeEvery, put, call to make async calls
easy.
- Generators are cancelable.
Immutable JS
- Redux reducer are pure functions and they need to modify the state passed to them, in an
immutable fashion.
- return {...state, {name: newValue}}
- But this is just destructuring at 1 level, if you have nested objects or lists there reference are still
the same.
- Immutable JS is a lib created by facebook, which helps fix these nuances of javascript. Its
also very efficient at managing data immutably.
- Supports a wide variety of data structures List, Map, OrderedMap, Set, OrderedSet etc.
- Data access and modification API is easy and consistent across data structures.
const { Map } = require('immutable');
const map1 = Map({ a: 1, b: 2, c: 3 });
const map2 = map1.set('b', 50);
map1.get('b') + " vs. " + map2.get('b'); // 2 vs. 50
- All the operations performed by the library are of immutable nature.
PropTypes validation (Type checking)
- Helps developers validate props passed to component in dev environment.
- This ensures proper usage of component props and gives errors in development time, if some
unparsable prop is passed and eliminates errors in production.
LoginForm.propTypes = {
username: PropTypes.string.isRequired,
Password: PropTypes.string.isRequired,
loginSubmit: PropTypes.func.isRequired,
};
- Can validate complex objects using json like schema.
UserList.propTypes = {
users: PropTypes.array.isRequired,
loginSubmit: PropTypes.func,
};
- Flow library helps in validating the entire app for prop types checking.
Type checking (cont…)
- PropTypes.element.isRequired,
- PropTypes.instanceOf(Message),
- PropTypes.oneOf(['News', 'Photos']),
- PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(Message)
]),
- PropTypes.arrayOf(PropTypes.number),
- PropTypes.objectOf(PropTypes.number),
- PropTypes.shape({
color: PropTypes.string,
fontSize: PropTypes.number
}),
React best practices
1. Use functional components as much as possible. (It helps minimize issues caused by this
keyword)
2. Use class components only when you need life cycle methods and/or local state. (even try
libs like recompose to totally eliminate class components).
3. Try to minimize the number of container components to one container per page.
4. Don’t give unnecessary state to any component.
5. Use concepts like selectors to minimize redux state and compute states wherever
possible.
6. Use tools like flow to do static type checking.
7. Use libs like immutable js to speed up redux state processing.
8. Keep async calls separate. (just like redux saga, even if you are using thunk figure out
ways to write the API calls separately instead of bloating up actions.js).
9. Unit test everything (jest, enzyme, mocha)
Tools that will make your life easy
1. react-javascript editor plugins for syntax highlighting
2. eslint and react-a11y, for static code checking in react apps.
3. editor config for proper code structure across IDEs and machines.
4. Emmet for jsx, helps you write jsx quickly with auto tag closing and template spitting.
5. Flow for static type checking of component props.
6. Define snippets to quickly write frequently used boilerplate codes.
7. Absolute path resolvers (no more, import Blah from ‘../../../../../blah)
8. class ==> className conversion tools. (helps you copy html templates directly without
worrying about jsx class attribute).
References
Topics:
1. React vs Redux state
2. Redux , Redux Architecture
3. react-redux apis
4. Selectors and reselect
5. Redux Saga
6. Immutable JS
7. Static type checking for react components
Pro tools:
1. Absolute path imports in create-react-app
2. Emmet for JSX in vs code
3. React snippets
More React insights:
1. ReactJS - Medium
● Questions ?
● Discussions…
Find the app below
1. Github repository
2. Live demo
Thank you

More Related Content

What's hot

React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
Vedran Blaženka
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
monikadeshmane
 
React state
React  stateReact  state
React state
Ducat
 
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
 
Reactjs workshop (1)
Reactjs workshop (1)Reactjs workshop (1)
Reactjs workshop (1)
Ahmed rebai
 
reactJS
reactJSreactJS
reactJS
Syam Santhosh
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
React hooks
React hooksReact hooks
React hooks
Ramy ElBasyouni
 
Introduction to jest
Introduction to jestIntroduction to jest
Introduction to jest
pksjce
 
State management in react applications (Statecharts)
State management in react applications (Statecharts)State management in react applications (Statecharts)
State management in react applications (Statecharts)
Tomáš Drenčák
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
NexThoughts Technologies
 
React and redux
React and reduxReact and redux
React and redux
Mystic Coders, LLC
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
Samundra khatri
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
MicroPyramid .
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
Nikolaus Graf
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
Thanh Tuong
 
React hooks
React hooksReact hooks
React hooks
Assaf Gannon
 
Manage react state with MobX
Manage react state with MobXManage react state with MobX
Manage react state with MobX
Asif Nawaz
 
React & Redux JS
React & Redux JS React & Redux JS
React & Redux JS
Hamed Farag
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
Yao Nien Chung
 

What's hot (20)

React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
 
React state
React  stateReact  state
React state
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
Reactjs workshop (1)
Reactjs workshop (1)Reactjs workshop (1)
Reactjs workshop (1)
 
reactJS
reactJSreactJS
reactJS
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
 
React hooks
React hooksReact hooks
React hooks
 
Introduction to jest
Introduction to jestIntroduction to jest
Introduction to jest
 
State management in react applications (Statecharts)
State management in react applications (Statecharts)State management in react applications (Statecharts)
State management in react applications (Statecharts)
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
React and redux
React and reduxReact and redux
React and redux
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
React hooks
React hooksReact hooks
React hooks
 
Manage react state with MobX
Manage react state with MobXManage react state with MobX
Manage react state with MobX
 
React & Redux JS
React & Redux JS React & Redux JS
React & Redux JS
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
 

Similar to Redux essentials

React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
Karmanjay Verma
 
downloads_introduction to redux.pptx
downloads_introduction to redux.pptxdownloads_introduction to redux.pptx
downloads_introduction to redux.pptx
NavneetKumar111924
 
FRONTEND BOOTCAMP 4.pptx
FRONTEND BOOTCAMP 4.pptxFRONTEND BOOTCAMP 4.pptx
FRONTEND BOOTCAMP 4.pptx
Ehtesham46
 
Redux
ReduxRedux
an Introduction to Redux
an Introduction to Reduxan Introduction to Redux
an Introduction to Redux
Amin Ashtiani
 
Getting started with React and Redux
Getting started with React and ReduxGetting started with React and Redux
Getting started with React and Redux
Paddy Lock
 
The Road To Redux
The Road To ReduxThe Road To Redux
The Road To Redux
Jeffrey Sanchez
 
Basic Fundamental of Redux
Basic Fundamental of ReduxBasic Fundamental of Redux
Basic Fundamental of Redux
InnovationM
 
React.js+Redux Workshops
React.js+Redux WorkshopsReact.js+Redux Workshops
React.js+Redux Workshops
Marcin Grzywaczewski
 
Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"
Flipkart
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
Ankit.Rustagi
 
Corso su ReactJS
Corso su ReactJSCorso su ReactJS
Corso su ReactJS
LinkMe Srl
 
Spfx with react redux
Spfx with react reduxSpfx with react redux
Spfx with react redux
Rajesh Kumar
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
StephieJohn
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree Technologies
Walking Tree Technologies
 
Introduction to React JS.pptx
Introduction to React JS.pptxIntroduction to React JS.pptx
Introduction to React JS.pptx
SHAIKIRFAN715544
 
React
ReactReact
React gsg presentation with ryan jung &amp; elias malik
React   gsg presentation with ryan jung &amp; elias malikReact   gsg presentation with ryan jung &amp; elias malik
React gsg presentation with ryan jung &amp; elias malik
Lama K Banna
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
AnmolPandita7
 

Similar to Redux essentials (20)

React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
downloads_introduction to redux.pptx
downloads_introduction to redux.pptxdownloads_introduction to redux.pptx
downloads_introduction to redux.pptx
 
FRONTEND BOOTCAMP 4.pptx
FRONTEND BOOTCAMP 4.pptxFRONTEND BOOTCAMP 4.pptx
FRONTEND BOOTCAMP 4.pptx
 
Redux
ReduxRedux
Redux
 
an Introduction to Redux
an Introduction to Reduxan Introduction to Redux
an Introduction to Redux
 
Getting started with React and Redux
Getting started with React and ReduxGetting started with React and Redux
Getting started with React and Redux
 
The Road To Redux
The Road To ReduxThe Road To Redux
The Road To Redux
 
Basic Fundamental of Redux
Basic Fundamental of ReduxBasic Fundamental of Redux
Basic Fundamental of Redux
 
React.js+Redux Workshops
React.js+Redux WorkshopsReact.js+Redux Workshops
React.js+Redux Workshops
 
Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Corso su ReactJS
Corso su ReactJSCorso su ReactJS
Corso su ReactJS
 
Spfx with react redux
Spfx with react reduxSpfx with react redux
Spfx with react redux
 
Presentation1
Presentation1Presentation1
Presentation1
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree Technologies
 
Introduction to React JS.pptx
Introduction to React JS.pptxIntroduction to React JS.pptx
Introduction to React JS.pptx
 
React
ReactReact
React
 
React gsg presentation with ryan jung &amp; elias malik
React   gsg presentation with ryan jung &amp; elias malikReact   gsg presentation with ryan jung &amp; elias malik
React gsg presentation with ryan jung &amp; elias malik
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
 

Recently uploaded

State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
ViralQR
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 

Recently uploaded (20)

State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 

Redux essentials

  • 1. Redux Effective State Management In React Applications Author: @rc-chandan
  • 2. Agenda 1. Local state vs Global state 2. Redux Architecture 3. Redux demo code (Todo console example) a. createStore(reducer, [preloadedState], [enhancer]) b. store.subscribe(callback) c. combineReducers({reducerKey: reducerValue, …}) 4. React with Redux code example a. react-redux b. Provider component c. Connect, mapStateToProps, mapDispatchToProps, Actions, reducers etc. 5. Selectors for computed state a. reselect library for memoization of computed state
  • 3. React State vs Redux State Local state (React) 1. Good for small application where there is not a lot of components, easier to write as it is inline. 2. In complex applications, local state is preferably used for short term states which changes rapidly and atomically and follows these conditions a. Other part of the application does not need that piece of state. b. We are not serializing the state as it is very minor UI level state like temporary textbox data. Applied filters to drop down menu or tables. c. If you want the application to resume with all these minute details then do not use inline component states. 3. Difficulties in sharing state between unrelated components. 4. There is no single source of truth. 5. Difficult to debug if the application components composition is complex. 6. There is no way to track changes to the state and going back to a previous state. 7. Serialization and deserialization of the local state is difficult.
  • 4. React State vs Redux State Global state (Redux) 1. Preferable for complex applications, as it creates a single state object for the entire application and removes logic to manipulate state from the component classes. 2. It is easier to serialize the whole application state and resume it afterwards. 3. Redux state store is immutable so history of the store is persisted, which gives features like time travel debugging. Also going back to previous state is easy. 4. Sharing a piece of state to different components is simple as any number of components can subscribe to that piece of the state. 5. Concepts like selectors can be used to reuse parts of state for creating new state structure for components if needed.
  • 6. Components of Redux Store: 1. Store contains the entire state of an application and manages it in an immutable fashion. 2. Store is created using createStore function provided by redux. 3. Store has utility functions like dispatch, subscribe, getState, replaceReducer etc. Actions: 1. Action objects are plain JS objects with a type property can optionally have some payload also. Dispatcher: 1. Dispatcher is a component of redux that dispatches a given action to all the reducers. 2. Dispatcher can be invoked by store.dispatch method. Reducer: 1. Function that takes a state and an action, returns the modified state. 2. For every action dispatched by dispatcher, all the reducer are notified.
  • 7. Todo list console app using only Redux Demo
  • 8. Redux in action (Todo list code)
  • 9. react-redux ● JS lib created by redux team to make redux easily pass state and action creators to react components. ● react-redux components and APIs: ○ <Provider store /> ■ React component that will auto subscribe to store passed to it. ○ connect(mapStateToProps, mapDispatchToProps)(TargetComponent) ■ Enhancer function that injects state and/or action creators to react components. ○ mapStateToProps(state, ownProps): ■ Injects state object as props to the target component ○ mapDispatchToProps(dispatch): ■ Injects action creator as props to the target component ○ bindActionCreators(actionCreators, dispatch): ■ Binds dispatch with action creators that are being passed to the target component
  • 10. Todo list app using React & Redux Live app demo
  • 11. Selectors ● JS functions that takes the state and/or condition, returns a computed state. ● Selectors are functions that make queries on the state object and returns the result. ● Useful for functionalities like conditional filtering, extracting a part of the state obj. ● Selectors are invoked while extracting state in mapStateToProps. ● State and props can be passed to the selector.
  • 12. Visibility filter using selectors in todo list app Selector code
  • 13. Reselect 1. Selectors are useful but they are inefficient, they do the same processing repeatedly for each related action dispatch. 2. This problem can be solved by implementing a memoization algo that remembers what was the previous value when similar input was processed by the selector. Thus reducing unnecessary repeated processing of the same data. 3. That is where reselect comes in, it is a memoization enabled selector lib created again by the awesome Redux team. 4. Reselect has a cache for already processed results and when equivalent queries are fired it returns result from the cache thus speeding up the selection process. 5. Selectors created by reselect are also chainable.
  • 14. Visibility filter using reselect in todo list app Reselect code
  • 15. Redux Saga (Side effect management) - Generator functions that listen to actions and yields new actions. - Great for side effect management like async calls and long running computations. - Makes react code look cleaner by moving side effects to separate file. - 100% unit testable by mocking API responses. E.g. function* login(action) { try{ const response = yield call(loginApi, action.username, action.password); if(response.ok) yield put(loginSuccessAction(user); } catch (error) { yield put(loginFailureAction(error); } } // subscribe to action type yield takeLatest(‘LOGIN_ACTION_TYPE, login); - Redux saga provides utility functions like takeLatest, takeEvery, put, call to make async calls easy. - Generators are cancelable.
  • 16. Immutable JS - Redux reducer are pure functions and they need to modify the state passed to them, in an immutable fashion. - return {...state, {name: newValue}} - But this is just destructuring at 1 level, if you have nested objects or lists there reference are still the same. - Immutable JS is a lib created by facebook, which helps fix these nuances of javascript. Its also very efficient at managing data immutably. - Supports a wide variety of data structures List, Map, OrderedMap, Set, OrderedSet etc. - Data access and modification API is easy and consistent across data structures. const { Map } = require('immutable'); const map1 = Map({ a: 1, b: 2, c: 3 }); const map2 = map1.set('b', 50); map1.get('b') + " vs. " + map2.get('b'); // 2 vs. 50 - All the operations performed by the library are of immutable nature.
  • 17. PropTypes validation (Type checking) - Helps developers validate props passed to component in dev environment. - This ensures proper usage of component props and gives errors in development time, if some unparsable prop is passed and eliminates errors in production. LoginForm.propTypes = { username: PropTypes.string.isRequired, Password: PropTypes.string.isRequired, loginSubmit: PropTypes.func.isRequired, }; - Can validate complex objects using json like schema. UserList.propTypes = { users: PropTypes.array.isRequired, loginSubmit: PropTypes.func, }; - Flow library helps in validating the entire app for prop types checking.
  • 18. Type checking (cont…) - PropTypes.element.isRequired, - PropTypes.instanceOf(Message), - PropTypes.oneOf(['News', 'Photos']), - PropTypes.oneOfType([ PropTypes.string, PropTypes.number, PropTypes.instanceOf(Message) ]), - PropTypes.arrayOf(PropTypes.number), - PropTypes.objectOf(PropTypes.number), - PropTypes.shape({ color: PropTypes.string, fontSize: PropTypes.number }),
  • 19. React best practices 1. Use functional components as much as possible. (It helps minimize issues caused by this keyword) 2. Use class components only when you need life cycle methods and/or local state. (even try libs like recompose to totally eliminate class components). 3. Try to minimize the number of container components to one container per page. 4. Don’t give unnecessary state to any component. 5. Use concepts like selectors to minimize redux state and compute states wherever possible. 6. Use tools like flow to do static type checking. 7. Use libs like immutable js to speed up redux state processing. 8. Keep async calls separate. (just like redux saga, even if you are using thunk figure out ways to write the API calls separately instead of bloating up actions.js). 9. Unit test everything (jest, enzyme, mocha)
  • 20. Tools that will make your life easy 1. react-javascript editor plugins for syntax highlighting 2. eslint and react-a11y, for static code checking in react apps. 3. editor config for proper code structure across IDEs and machines. 4. Emmet for jsx, helps you write jsx quickly with auto tag closing and template spitting. 5. Flow for static type checking of component props. 6. Define snippets to quickly write frequently used boilerplate codes. 7. Absolute path resolvers (no more, import Blah from ‘../../../../../blah) 8. class ==> className conversion tools. (helps you copy html templates directly without worrying about jsx class attribute).
  • 21. References Topics: 1. React vs Redux state 2. Redux , Redux Architecture 3. react-redux apis 4. Selectors and reselect 5. Redux Saga 6. Immutable JS 7. Static type checking for react components Pro tools: 1. Absolute path imports in create-react-app 2. Emmet for JSX in vs code 3. React snippets More React insights: 1. ReactJS - Medium
  • 22. ● Questions ? ● Discussions… Find the app below 1. Github repository 2. Live demo Thank you