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

PDF
Redux Saga - Under the hood
PPTX
Redux workshop
PPTX
React Class Components vs Functional Components: Which is Better?
PDF
Introduction to Redux
PPTX
Redux training
PDF
React and redux
PDF
An Introduction to ReactJS
PDF
Let's Redux!
Redux Saga - Under the hood
Redux workshop
React Class Components vs Functional Components: Which is Better?
Introduction to Redux
Redux training
React and redux
An Introduction to ReactJS
Let's Redux!

What's hot (20)

PDF
An Introduction to Redux
PDF
React JS and why it's awesome
PDF
State Management in Angular/React
PPTX
React workshop
PDF
진민완 포트폴리오
PDF
React.js and Redux overview
PDF
The virtual DOM and how react uses it internally
PPTX
React + Redux Introduction
PDF
react redux.pdf
PDF
Redux Toolkit - Quick Intro - 2022
PPTX
React JS: A Secret Preview
PPTX
State management in react applications (Statecharts)
PDF
PPTX
reactJS
PDF
Understanding React hooks | Walkingtree Technologies
PDF
React js
PPTX
React js programming concept
PDF
Redux Sagas - React Alicante
PPTX
React state
PPTX
React js for beginners
An Introduction to Redux
React JS and why it's awesome
State Management in Angular/React
React workshop
진민완 포트폴리오
React.js and Redux overview
The virtual DOM and how react uses it internally
React + Redux Introduction
react redux.pdf
Redux Toolkit - Quick Intro - 2022
React JS: A Secret Preview
State management in react applications (Statecharts)
reactJS
Understanding React hooks | Walkingtree Technologies
React js
React js programming concept
Redux Sagas - React Alicante
React state
React js for beginners
Ad

Similar to Redux essentials (20)

PPTX
Maintaining sanity in a large redux app
PDF
Building React Applications with Redux
PDF
Materi Modern React Redux Power Point.pdf
PDF
Redux js
PDF
Let's discover React and Redux with TypeScript
PDF
Getting started with React and Redux
PDF
The Road To Redux
PDF
Understanding redux
PDF
A React Journey
PDF
ReactRedux.pdf
PPTX
Introduction to react and redux
PDF
React state managmenet with Redux
PPTX
React/Redux
PPTX
Academy PRO: React JS. Redux & Tooling
PPTX
Getting started with Redux js
PDF
Evan Schultz - Angular Summit - 2016
PDF
Advanced Redux architecture - WHAT/WHEN/WHY/HOW
PDF
Making react part of something greater
PPTX
STATE MANAGEMENT IN REACT [Autosaved].pptx
PPTX
Maintaining sanity in a large redux app
Building React Applications with Redux
Materi Modern React Redux Power Point.pdf
Redux js
Let's discover React and Redux with TypeScript
Getting started with React and Redux
The Road To Redux
Understanding redux
A React Journey
ReactRedux.pdf
Introduction to react and redux
React state managmenet with Redux
React/Redux
Academy PRO: React JS. Redux & Tooling
Getting started with Redux js
Evan Schultz - Angular Summit - 2016
Advanced Redux architecture - WHAT/WHEN/WHY/HOW
Making react part of something greater
STATE MANAGEMENT IN REACT [Autosaved].pptx
Ad

Recently uploaded (20)

PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
Modernizing your data center with Dell and AMD
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Machine learning based COVID-19 study performance prediction
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Electronic commerce courselecture one. Pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Big Data Technologies - Introduction.pptx
Modernizing your data center with Dell and AMD
Encapsulation_ Review paper, used for researhc scholars
Advanced methodologies resolving dimensionality complications for autism neur...
Understanding_Digital_Forensics_Presentation.pptx
Machine learning based COVID-19 study performance prediction
The Rise and Fall of 3GPP – Time for a Sabbatical?
Reach Out and Touch Someone: Haptics and Empathic Computing
NewMind AI Monthly Chronicles - July 2025
Review of recent advances in non-invasive hemoglobin estimation
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Network Security Unit 5.pdf for BCA BBA.
Electronic commerce courselecture one. Pdf
Chapter 3 Spatial Domain Image Processing.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Building Integrated photovoltaic BIPV_UPV.pdf

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