SlideShare a Scribd company logo
1 of 22
Download to read offline
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

What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjsmanojbkalla
 
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
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6Rob Eisenberg
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.jsEmanuele DelBono
 
State Management in Angular/React
State Management in Angular/ReactState Management in Angular/React
State Management in Angular/ReactDEV Cafe
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentationritika1
 
Redux Saga - Under the hood
Redux Saga - Under the hoodRedux Saga - Under the hood
Redux Saga - Under the hoodWaqqas Jabbar
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hookPiyush Jamwal
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentationThanh Tuong
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overviewAlex Bachuk
 

What's hot (20)

Reactjs
Reactjs Reactjs
Reactjs
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjs
 
State management in react applications (Statecharts)
State management in react applications (Statecharts)State management in react applications (Statecharts)
State management in react applications (Statecharts)
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
React Hooks
React HooksReact Hooks
React Hooks
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
Vue.js
Vue.jsVue.js
Vue.js
 
Introduction à React
Introduction à ReactIntroduction à React
Introduction à React
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
State Management in Angular/React
State Management in Angular/ReactState Management in Angular/React
State Management in Angular/React
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
Reactjs
ReactjsReactjs
Reactjs
 
Redux Saga - Under the hood
Redux Saga - Under the hoodRedux Saga - Under the hood
Redux Saga - Under the hood
 
Redux workshop
Redux workshopRedux workshop
Redux workshop
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hook
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
reactJS
reactJSreactJS
reactJS
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
ReactJS
ReactJSReactJS
ReactJS
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
 

Similar to Redux State Management in React Apps

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.pptxNavneetKumar111924
 
FRONTEND BOOTCAMP 4.pptx
FRONTEND BOOTCAMP 4.pptxFRONTEND BOOTCAMP 4.pptx
FRONTEND BOOTCAMP 4.pptxEhtesham46
 
an Introduction to Redux
an Introduction to Reduxan Introduction to Redux
an Introduction to ReduxAmin Ashtiani
 
Getting started with React and Redux
Getting started with React and ReduxGetting started with React and Redux
Getting started with React and ReduxPaddy Lock
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksSamundra khatri
 
Basic Fundamental of Redux
Basic Fundamental of ReduxBasic Fundamental of Redux
Basic Fundamental of ReduxInnovationM
 
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
 
Corso su ReactJS
Corso su ReactJSCorso su ReactJS
Corso su ReactJSLinkMe Srl
 
Spfx with react redux
Spfx with react reduxSpfx with react redux
Spfx with react reduxRajesh Kumar
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react jsStephieJohn
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesWalking Tree Technologies
 
Introduction to React JS.pptx
Introduction to React JS.pptxIntroduction to React JS.pptx
Introduction to React JS.pptxSHAIKIRFAN715544
 

Similar to Redux State Management in React Apps (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
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
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
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 
React
ReactReact
React
 

Recently uploaded

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 

Recently uploaded (20)

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 

Redux State Management in React Apps

  • 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