SlideShare a Scribd company logo
REDUX
DASER DAVID - NHUB
REDUX - ACTION
- Actions are payloads of information that send
data from your application to your store.
- They are the only source of information for the
store.
- You send them to the store using store.dispatch().
REDUX - ACTION
NOTE: PAY CLOSE ATTENTION TO
store.dispatch()
IT IS USED WHEN SENDING ACTION TO STORES.
REDUX - ACTION
const ADD_TODO = 'ADD_TODO'
{
type: ADD_TODO,
text: 'Build my first Redux app'
}
NOTE: type is a must, you can add other things provided you meet
the type requirements.
REDUX - ACTION
- Actions are plain JavaScript objects.
- Actions must have a type property that indicates the type
of action being performed.
- Types should typically be defined as string constants.
- Once your app is large enough, you may want to move them
into a separate module.
REDUX - ACTION
import { ADD_TODO, REMOVE_TODO } from '../actionTypes'
../actionTypes.JS
export const ADD_TODO = 'ADD_TODO'
export const REMOVE_TODO = 'REMOVE_TODO'
REDUX - ACTION - ACTION CREATORS
Action creators are exactly that—functions that
create actions.
It's easy to conflate the terms “action” and “action
creator,” so do your best to use the proper term.
EXERCISE 1
- CONSTRUCT AN ACTION
- CONSTRUCT AN ACTION CREATOR
REDUX - ACTION - ACTION CREATORS
//ACTION
export const ADD_TODO = 'ADD_TODO'
//ACTION CREATOR
export function addTodo(text)
{
return { type: ADD_TODO, text }
}
REDUX - REDUCERS
- Reducers specify how the application's state
changes in response to actions sent to the store.
- Remember that actions only describe the fact that
something happened, but don't describe how the
application's state changes.
REDUX - REDUCERS
The reducer is a pure function that takes the previous state and
an action, and returns the next state.
(previousState, action) => newState
REDUX - REDUCERS
PURE FUNCTION
function priceAfterTax(productPrice) {
return (productPrice * 0.20) + productPrice;
}
REDUX - REDUCERS
IMPURE
var tax = 20;
function calculateTax(productPrice) {
return (productPrice * (tax/100)) + productPrice;
}
REDUX - REDUCERS
Things you should never do inside a reducer:
- Mutate its arguments;
- Perform side effects like API calls and routing transitions;
- Call non-pure functions, e.g. Date.now() or Math.random().
REDUX - REDUCERS
Given the same arguments, it should calculate the
next state and return it.
- No surprises.
- No side effects.
- No API calls.
- No mutations.
- Just a calculation.
LETS WALK DOWN SOME DEEP
actions.js
export const VisibilityFilters = {
SHOW_ALL: 'SHOW_ALL',
SHOW_COMPLETED: 'SHOW_COMPLETED',
SHOW_ACTIVE: 'SHOW_ACTIVE'
}
We'll start by specifying the initial state.
Redux will call our reducer with an undefined state
for the first time.
This is our chance to return the initial state of our
app.
ALWAYS HAVE AN INITIAL STATE IN MIND
import { VisibilityFilters } from './actions'
const initialState = {
visibilityFilter: VisibilityFilters.SHOW_ALL,
todos: []
}
function todoApp(state, action) {
if (typeof state === 'undefined') {
return initialState
}
return state
}
function todoApp(state = initialState,
action) {
// For now, don't handle any actions
// and just return the state given to us.
return state
}
Object.assign()
Object.assign(target, ...sources)
Parameters
Target
The target object.
Sources
The source object(s).
Return value
The target object.
Cloning
var obj = { a: 1 };
var copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
function todoApp(state = initialState, action) {
switch (action.type) {
case SET_VISIBILITY_FILTER:
return Object.assign({}, state, {
visibilityFilter: action.filter
})
default:
return state
}
NOTE:
1. We don't mutate the state.
- We create a copy with Object.assign().
- Object.assign(state, { visibilityFilter: action.filter }) is also wrong: it will
mutate the first argument.
- You must supply an empty object as the first parameter.
- You can also enable the object spread operator proposal to write { ...state,
...newState } instead.
2. We return the previous state in the default case. It's important to return
the previous state for any unknown action.
LETS SEE THE ACTION?
export function setVisibilityFilter(filter) {
return { type: SET_VISIBILITY_FILTER, filter }
}
GOING DEEPER - REDUCER
case ADD_TODO:
return Object.assign({}, state, {
todos: [
...state.todos,
{
text: action.text,
completed: false
} ]
})
GOING DEEPER - ACTION
export function addTodo(text) {
return { type: ADD_TODO, text }
}
PROBLEMS AT SCALE
When the app is larger, we can split the reducers into
separate files and keep them completely independent and
managing different data domains.
SOLUTION:
- Redux provides a utility called combineReducers()
- All combineReducers() does is generate a function
that calls your reducers with the slices of state
selected according to their keys, and combining their
results into a single object again.
REDUX - STORE
we defined the actions that represent the facts
about “what happened” and the reducers that
update the state according to those actions.
The Store is the object that brings them together.
REDUX - STORE
The store has the following responsibilities:
- Holds application state;
- Allows access to state via getState();
- Allows state to be updated via dispatch(action);
- Registers listeners via subscribe(listener);
- Handles unregistering of listeners via the function returned by
subscribe(listener).
REDUX - STORE
It's important to note that you'll only have a single
store in a Redux application.
REDUX - STORE
- It's easy to create a store if you have a reducer.
- We used combineReducers() to combine several
reducers into one.
- We will now import it, and pass it to
createStore().
REDUX - STORE
import { createStore } from 'redux'
import todoApp from './reducers'
let store = createStore(todoApp)
REDUX - STORE
You may optionally specify the initial state as the second
argument to createStore(). This is useful for hydrating the state of
the client to match the state of a Redux application running on the
server.
let store = createStore(todoApp,
window.STATE_FROM_SERVER)
Dispatching Actions
store.dispatch(addTodo('Learn about actions'))
DATA FLOW
Redux architecture revolves around a strict unidirectional
data flow.
This means that all data in an application follows the same
lifecycle pattern, making the logic of your app more
predictable and easier to understand. It also encourages
data normalization, so that you don't end up with multiple,
independent copies of the same data that are unaware of
one another.
DATA FLOW - 4 STEPS OF REDUX
1. You call store.dispatch(action).
An action is a plain object describing what happened. For example:
{ type: 'LIKE_ARTICLE', articleId: 42 }
{ type: 'FETCH_USER_SUCCESS', response: { id: 3, name: 'Mary' } }
{ type: 'ADD_TODO', text: 'Read the Redux docs.' }
Think of an action as a very brief snippet of news. “Mary liked article 42.” or “‘Read the Redux docs.' was
added to the list of todos.”
You can call store.dispatch(action) from anywhere in your app, including components and XHR callbacks,
or even at scheduled intervals.
DATA FLOW - 4 STEPS OF REDUX
2. The Redux store calls the reducer function you gave it.
The store will pass two arguments to the reducer: the current state
tree and the action. For example, in the todo app, the root reducer
might receive something like this:
let previousState = {
visibleTodoFilter: 'SHOW_ALL',
todos: [
{
text: 'Read the docs.',
complete: false
}
]
}
// The action being performed (adding a todo)
let action = {
type: 'ADD_TODO',
text: 'Understand the flow.'
}
// Your reducer returns the next application state
let nextState = todoApp(previousState, action)
DATA FLOW - 4 STEPS OF REDUX
3. The root reducer may combine the output of multiple reducers into a
single state tree.
REMEMBER
How you structure the root reducer is completely up to you. Redux ships with
a combineReducers() helper function, useful for “splitting” the root reducer
into separate functions that each manage one branch of the state tree.
function todos(state = [], action) {
// Somehow calculate it...
return nextState
}
function visibleTodoFilter(state = 'SHOW_ALL', action) {
// Somehow calculate it...
return nextState
}
let todoApp = combineReducers({
todos,
visibleTodoFilter
})
When you emit an action, todoApp returned by combineReducers will call both reducers:
let nextTodos = todos(state.todos, action)
let nextVisibleTodoFilter = visibleTodoFilter(state.visibleTodoFilter, action)
It will then combine both sets of results into a single state tree:
return {
todos: nextTodos,
visibleTodoFilter: nextVisibleTodoFilter
}
While combineReducers() is a handy helper utility, you don't have to use it; feel free to write your
own root reducer!
DATA FLOW - 4 STEPS OF REDUX
4. The Redux store saves the complete state tree returned by the root
reducer.
This new tree is now the next state of your app! Every listener
registered with store.subscribe(listener) will now be invoked; listeners
may call store.getState() to get the current state.
Now, the UI can be updated to reflect the new state. If you use bindings
like React Redux, this is the point at which
component.setState(newState) is called.
THANK YOU….

More Related Content

PPTX
Redux workshop
PDF
Introduction to Redux
PDF
An Introduction to Redux
PPTX
React + Redux Introduction
PPTX
React web development
PPTX
Introduction to Facebook React
PPTX
PPTX
Introduction to React
Redux workshop
Introduction to Redux
An Introduction to Redux
React + Redux Introduction
React web development
Introduction to Facebook React
Introduction to React

What's hot (20)

PDF
Important React Hooks
PPTX
Introduction to react and redux
PPTX
React introduction
PDF
react redux.pdf
PDF
React
PPTX
React with Redux
PPTX
React hooks
PDF
React state managmenet with Redux
PDF
Understanding react hooks
PPTX
Intro to React
PPTX
React hooks
PDF
React
PDF
React js
PDF
Introduction to React JS
PPT
React js
PDF
React and redux
PDF
React new features and intro to Hooks
PDF
ReactJS presentation
PPTX
Introduction to React JS for beginners | Namespace IT
PPTX
React hooks
Important React Hooks
Introduction to react and redux
React introduction
react redux.pdf
React
React with Redux
React hooks
React state managmenet with Redux
Understanding react hooks
Intro to React
React hooks
React
React js
Introduction to React JS
React js
React and redux
React new features and intro to Hooks
ReactJS presentation
Introduction to React JS for beginners | Namespace IT
React hooks
Ad

Similar to Redux training (20)

PDF
Understanding redux
PPTX
Getting started with Redux js
PDF
Redux essentials
PPTX
Maintaining sanity in a large redux app
PPTX
PDF
React Redux Tutorial | Redux Tutorial for Beginners | React Redux Training | ...
PDF
Redux js
PDF
[@NaukriEngineering] Flux Architecture
PPTX
Reducers+flux=redux
PDF
Intro to Redux | DreamLab Academy #3
PPTX
downloads_introduction to redux.pptx
PDF
Redux tutorial - intro to Redux by GetLittleTech
PDF
Evan Schultz - Angular Summit - 2016
PDF
Let's discover React and Redux with TypeScript
PPTX
an Introduction to Redux
PDF
Advanced Redux architecture - WHAT/WHEN/WHY/HOW
PDF
Angular2 and Redux - up & running - Nir Kaufman - Codemotion Amsterdam 2016
PDF
Redux Deep Dive - ReactFoo Pune 2018
PDF
Building React Applications with Redux
PDF
Getting started with React and Redux
Understanding redux
Getting started with Redux js
Redux essentials
Maintaining sanity in a large redux app
React Redux Tutorial | Redux Tutorial for Beginners | React Redux Training | ...
Redux js
[@NaukriEngineering] Flux Architecture
Reducers+flux=redux
Intro to Redux | DreamLab Academy #3
downloads_introduction to redux.pptx
Redux tutorial - intro to Redux by GetLittleTech
Evan Schultz - Angular Summit - 2016
Let's discover React and Redux with TypeScript
an Introduction to Redux
Advanced Redux architecture - WHAT/WHEN/WHY/HOW
Angular2 and Redux - up & running - Nir Kaufman - Codemotion Amsterdam 2016
Redux Deep Dive - ReactFoo Pune 2018
Building React Applications with Redux
Getting started with React and Redux
Ad

Recently uploaded (20)

PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
III.4.1.2_The_Space_Environment.p pdffdf
PDF
PPT on Performance Review to get promotions
PPTX
Construction Project Organization Group 2.pptx
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
Sustainable Sites - Green Building Construction
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
Safety Seminar civil to be ensured for safe working.
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
737-MAX_SRG.pdf student reference guides
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
PPTX
Geodesy 1.pptx...............................................
PPT
Mechanical Engineering MATERIALS Selection
Embodied AI: Ushering in the Next Era of Intelligent Systems
III.4.1.2_The_Space_Environment.p pdffdf
PPT on Performance Review to get promotions
Construction Project Organization Group 2.pptx
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Internet of Things (IOT) - A guide to understanding
CYBER-CRIMES AND SECURITY A guide to understanding
Sustainable Sites - Green Building Construction
R24 SURVEYING LAB MANUAL for civil enggi
Safety Seminar civil to be ensured for safe working.
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
737-MAX_SRG.pdf student reference guides
bas. eng. economics group 4 presentation 1.pptx
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
Geodesy 1.pptx...............................................
Mechanical Engineering MATERIALS Selection

Redux training

  • 2. REDUX - ACTION - Actions are payloads of information that send data from your application to your store. - They are the only source of information for the store. - You send them to the store using store.dispatch().
  • 3. REDUX - ACTION NOTE: PAY CLOSE ATTENTION TO store.dispatch() IT IS USED WHEN SENDING ACTION TO STORES.
  • 4. REDUX - ACTION const ADD_TODO = 'ADD_TODO' { type: ADD_TODO, text: 'Build my first Redux app' } NOTE: type is a must, you can add other things provided you meet the type requirements.
  • 5. REDUX - ACTION - Actions are plain JavaScript objects. - Actions must have a type property that indicates the type of action being performed. - Types should typically be defined as string constants. - Once your app is large enough, you may want to move them into a separate module.
  • 6. REDUX - ACTION import { ADD_TODO, REMOVE_TODO } from '../actionTypes' ../actionTypes.JS export const ADD_TODO = 'ADD_TODO' export const REMOVE_TODO = 'REMOVE_TODO'
  • 7. REDUX - ACTION - ACTION CREATORS Action creators are exactly that—functions that create actions. It's easy to conflate the terms “action” and “action creator,” so do your best to use the proper term.
  • 8. EXERCISE 1 - CONSTRUCT AN ACTION - CONSTRUCT AN ACTION CREATOR
  • 9. REDUX - ACTION - ACTION CREATORS //ACTION export const ADD_TODO = 'ADD_TODO' //ACTION CREATOR export function addTodo(text) { return { type: ADD_TODO, text } }
  • 10. REDUX - REDUCERS - Reducers specify how the application's state changes in response to actions sent to the store. - Remember that actions only describe the fact that something happened, but don't describe how the application's state changes.
  • 11. REDUX - REDUCERS The reducer is a pure function that takes the previous state and an action, and returns the next state. (previousState, action) => newState
  • 12. REDUX - REDUCERS PURE FUNCTION function priceAfterTax(productPrice) { return (productPrice * 0.20) + productPrice; }
  • 13. REDUX - REDUCERS IMPURE var tax = 20; function calculateTax(productPrice) { return (productPrice * (tax/100)) + productPrice; }
  • 14. REDUX - REDUCERS Things you should never do inside a reducer: - Mutate its arguments; - Perform side effects like API calls and routing transitions; - Call non-pure functions, e.g. Date.now() or Math.random().
  • 15. REDUX - REDUCERS Given the same arguments, it should calculate the next state and return it. - No surprises. - No side effects. - No API calls. - No mutations. - Just a calculation.
  • 16. LETS WALK DOWN SOME DEEP actions.js export const VisibilityFilters = { SHOW_ALL: 'SHOW_ALL', SHOW_COMPLETED: 'SHOW_COMPLETED', SHOW_ACTIVE: 'SHOW_ACTIVE' }
  • 17. We'll start by specifying the initial state. Redux will call our reducer with an undefined state for the first time. This is our chance to return the initial state of our app. ALWAYS HAVE AN INITIAL STATE IN MIND
  • 18. import { VisibilityFilters } from './actions' const initialState = { visibilityFilter: VisibilityFilters.SHOW_ALL, todos: [] }
  • 19. function todoApp(state, action) { if (typeof state === 'undefined') { return initialState } return state }
  • 20. function todoApp(state = initialState, action) { // For now, don't handle any actions // and just return the state given to us. return state }
  • 21. Object.assign() Object.assign(target, ...sources) Parameters Target The target object. Sources The source object(s). Return value The target object.
  • 22. Cloning var obj = { a: 1 }; var copy = Object.assign({}, obj); console.log(copy); // { a: 1 }
  • 23. function todoApp(state = initialState, action) { switch (action.type) { case SET_VISIBILITY_FILTER: return Object.assign({}, state, { visibilityFilter: action.filter }) default: return state }
  • 24. NOTE: 1. We don't mutate the state. - We create a copy with Object.assign(). - Object.assign(state, { visibilityFilter: action.filter }) is also wrong: it will mutate the first argument. - You must supply an empty object as the first parameter. - You can also enable the object spread operator proposal to write { ...state, ...newState } instead. 2. We return the previous state in the default case. It's important to return the previous state for any unknown action.
  • 25. LETS SEE THE ACTION? export function setVisibilityFilter(filter) { return { type: SET_VISIBILITY_FILTER, filter } }
  • 26. GOING DEEPER - REDUCER case ADD_TODO: return Object.assign({}, state, { todos: [ ...state.todos, { text: action.text, completed: false } ] })
  • 27. GOING DEEPER - ACTION export function addTodo(text) { return { type: ADD_TODO, text } }
  • 28. PROBLEMS AT SCALE When the app is larger, we can split the reducers into separate files and keep them completely independent and managing different data domains.
  • 29. SOLUTION: - Redux provides a utility called combineReducers() - All combineReducers() does is generate a function that calls your reducers with the slices of state selected according to their keys, and combining their results into a single object again.
  • 30. REDUX - STORE we defined the actions that represent the facts about “what happened” and the reducers that update the state according to those actions. The Store is the object that brings them together.
  • 31. REDUX - STORE The store has the following responsibilities: - Holds application state; - Allows access to state via getState(); - Allows state to be updated via dispatch(action); - Registers listeners via subscribe(listener); - Handles unregistering of listeners via the function returned by subscribe(listener).
  • 32. REDUX - STORE It's important to note that you'll only have a single store in a Redux application.
  • 33. REDUX - STORE - It's easy to create a store if you have a reducer. - We used combineReducers() to combine several reducers into one. - We will now import it, and pass it to createStore().
  • 34. REDUX - STORE import { createStore } from 'redux' import todoApp from './reducers' let store = createStore(todoApp)
  • 35. REDUX - STORE You may optionally specify the initial state as the second argument to createStore(). This is useful for hydrating the state of the client to match the state of a Redux application running on the server. let store = createStore(todoApp, window.STATE_FROM_SERVER)
  • 37. DATA FLOW Redux architecture revolves around a strict unidirectional data flow. This means that all data in an application follows the same lifecycle pattern, making the logic of your app more predictable and easier to understand. It also encourages data normalization, so that you don't end up with multiple, independent copies of the same data that are unaware of one another.
  • 38. DATA FLOW - 4 STEPS OF REDUX 1. You call store.dispatch(action). An action is a plain object describing what happened. For example: { type: 'LIKE_ARTICLE', articleId: 42 } { type: 'FETCH_USER_SUCCESS', response: { id: 3, name: 'Mary' } } { type: 'ADD_TODO', text: 'Read the Redux docs.' } Think of an action as a very brief snippet of news. “Mary liked article 42.” or “‘Read the Redux docs.' was added to the list of todos.” You can call store.dispatch(action) from anywhere in your app, including components and XHR callbacks, or even at scheduled intervals.
  • 39. DATA FLOW - 4 STEPS OF REDUX 2. The Redux store calls the reducer function you gave it. The store will pass two arguments to the reducer: the current state tree and the action. For example, in the todo app, the root reducer might receive something like this:
  • 40. let previousState = { visibleTodoFilter: 'SHOW_ALL', todos: [ { text: 'Read the docs.', complete: false } ] }
  • 41. // The action being performed (adding a todo) let action = { type: 'ADD_TODO', text: 'Understand the flow.' }
  • 42. // Your reducer returns the next application state let nextState = todoApp(previousState, action)
  • 43. DATA FLOW - 4 STEPS OF REDUX 3. The root reducer may combine the output of multiple reducers into a single state tree. REMEMBER How you structure the root reducer is completely up to you. Redux ships with a combineReducers() helper function, useful for “splitting” the root reducer into separate functions that each manage one branch of the state tree.
  • 44. function todos(state = [], action) { // Somehow calculate it... return nextState } function visibleTodoFilter(state = 'SHOW_ALL', action) { // Somehow calculate it... return nextState } let todoApp = combineReducers({ todos, visibleTodoFilter })
  • 45. When you emit an action, todoApp returned by combineReducers will call both reducers: let nextTodos = todos(state.todos, action) let nextVisibleTodoFilter = visibleTodoFilter(state.visibleTodoFilter, action) It will then combine both sets of results into a single state tree: return { todos: nextTodos, visibleTodoFilter: nextVisibleTodoFilter } While combineReducers() is a handy helper utility, you don't have to use it; feel free to write your own root reducer!
  • 46. DATA FLOW - 4 STEPS OF REDUX 4. The Redux store saves the complete state tree returned by the root reducer. This new tree is now the next state of your app! Every listener registered with store.subscribe(listener) will now be invoked; listeners may call store.getState() to get the current state. Now, the UI can be updated to reflect the new state. If you use bindings like React Redux, this is the point at which component.setState(newState) is called.