SlideShare a Scribd company logo
Redux
yet another flux implementation ?
Nils Petersohn | twitter.com/snackycracky | alan@turing.technology
agenda
• main ideas and overview of redux components
• actions as pure functions
• immutability and mutations in redux
• sync flow
• functional composition and redux middleware
• async actions
• reactjs bindings
• experiences refactoring to redux
what does it do ?
• architecture to manage state
• Redux attempts to make state mutations predictable by putting
restrictions on how and when updates can happen.
• does not attempt to solve the problems that Relay wants to
solve
• Relies heavily on functional programming paradigms
ideas and components
• Single source of truth
• The state is stored in an object tree inside a single store.
• State is read-only
• The only way to mutate the state is to emit an action, an
object describing what happened.
• Mutations are written as pure functions
• logic for changes triggered by those actions is inside
“pure reducers”.
pure functions
• are encapsulated constructs with deterministic
behaviour
• trivial but predictable aka. easy testable
• end up with hundreds of ever repeating arguments?
• no, higher order functions and function compositions
to the rescue
redux-actions as pure
functions
• important difference to Flux: no dispatching inside
the action
• there is no Dispatcher at all; pure functions do not
need to be managed, they need to be composed.
//Action

function addGoing(memberId){

return { action: "ADD_GOING", memberId: memberId };

}
immutability
• once “something” is created, it can’t be changed anymore
• how to mutate then ?
• make a new “something” with the desired changes
• benefits ?
• 100% sure that this “something” is not changed while being
passed around in the flow.
• don't have to worry about the underlying data being changed by
another entity
• (concurrency)
reducers
• invoked with current state and the desired actions as
arguments to change the state create a new state
• one store also means one reducer ?
• no, there can be multiple reducers for the central
store. Also reducers calling other reducers is
common to modify deeply nested states.
• redux will bind them together with
`combineReducers(reducerList)` where each
of them manages it’s own part of the global state
example: List on meetup-page where people can RSVP
immutability with reducers
const initState = Immutable.Map({

title: "", organiser: "", founded: "", going: [], notGoing: []

})



//reducer

function reducingMeetupPage(state = initState, action){

if(action.type == "ADD_GOING"){

return state.update("going", (going) => going.add(action.memberId));

}

if(action.type == “ADD_NOT_GOING”){ 

let clonedNotGoing = state.toJS().notGoing;

clonedNotGoing.push(action.memberId);
//ES6 spread syntax w/o ImmutableJS:

return {...state.toJS(), notGoing: clonedNotGoing};

}

return state;

}



//Actions

function addGoing(memberId){

return { action: "ADD_GOING", memberId: memberId }; //pure: without dispatching

}



function addNotGoing(memberId){

return { action: “ADD_NOT_GOING", memberId: memberId};

}
a smart react container
• connects to everything redux.
• actions and state are injected in the props
• avoid rendering HTML, let the dumb components do that
import {addGoing, addNotGoing} from "reducers/meetup"

import {hideAlerts} from "reducers/users" 



@connect(

state => ({

going: state.visibleMeetup.going,

notGoing: state.visibleMeetup.notGoing,

comments: state.visibleMeetup.comments,

memberId: state.user.memberId,

userAlerts: state.user.alerts

}), 

dispatch => bindActionCreators({

addGoing, 

addNotGoing, 

hideAlerts}, dispatch)) 

export default class MeetupPage extends Component {

render() {

const {going,notGoing,addGoing,addNotGoing,userAlerts,hideAlerts,memberId} = this.props;

<div>

<UserInfo userNotifications={userAlerts} hideAlerts={hideAlerts}/> 

<AllOtherPageContent allOtherActions={...} />

<GoingNotGoingComponent addGoing={addGoing} going={going} ... />

</div>

}

}
a dumb react component
export default class GoingNotGoingComponent extends Component {

render() {



const {going, notGoing, memberId, addGoing, addNotGoing}= this.props;



<div>

<button onClick={addGoing.bind(null, memberId)}>I am Going</button>

<ul className="going">

{going.map(member => return <li>{member}</li>)}

</ul>



<hr/>



<button onClick={addNotGoing.bind(null, memberId)}>I am NOT Going</button>

<ul className="notGoing">

{going.map(member => <li>{user}</li>)}

</ul>

</div>

}

}
• does not know anything about redux.
• actions and state are injected in the props … again
• final payload is rendered here
sync flow
• Action -> Reducer -> SmartContainer -> DumbComponent
ui
smart Component
injected state
imported
Action Objects
wrapped with
dispatch
redux
Action
Objects / functions
ReducerReducer
Store
dumb Component
references to actions
dumb Component
references to actions
function composition
• currying = preconfigured functions being configured a little more
http://stackoverflow.com/a/218055/170881
• checkout lodashs collection of higher order functions
like _.compose, _.curry, _.partial
middleware architecture with
functional composition
• It provides a third-party extension point between dispatching an
action, and the moment it reaches the reducer.
• People use Redux middleware for logging, crash reporting, talking
to an asynchronous API, routing, and more.
const logger = store => next => action => {

console.log('dispatching', action);

let result = next(action);

console.log('next state', store.getState());

return result;

};



let createStoreWithMiddleware = applyMiddleware(logger,...)(createStore);

let myApp = combineReducers(reducers);

let store = createStoreWithMiddleware(myApp);
Async Actions• middleware can be used to check if the action contains promises and
can execute them
• In more complex apps you might want to use Rx for resolving async
actions instead, and feed an observable of actions into Redux.
export default function asyncActionsMiddleware(client) {

return ({dispatch, getState}) => {

return next => action => {

const { promise, types, ...rest } = action;


if (!promise) {

return next(action);

}



const [REQUEST, SUCCESS, FAILURE] = types;

next({...rest, type: REQUEST});

return promise(client).then(

(result) => next({...rest, result, type: SUCCESS}),

(error) => next({...rest, error, type: FAILURE})

).catch((error)=> {

console.error('MIDDLEWARE ERROR:', error);

next({...rest, error, type: FAILURE});

});

};

};

}

one Async Flow = two Sync Flows
redux
Action
Objects / functions
ReducerReducer
Store
Middleware for API-
Calls
backend
1. request
1. disposing action for
REQUESTING_DATA
2. response
2. disposing action for
DATA_RECIEVED
ui
smart Component
injected state
imported
Action Objects
wrapped with
dispatch
dumb Component
references to actions
dumb Component
references to actions
1. show spinner
2. show data
API Endpoints
react and flux inventory
• 4 Views, 20 react-components and 12 stores.
• one central view with a datagrid where data is shown
• 6 stores in 3 views contribute to the datagrid's display
properties:
• UserRolesStore, datagrid(-DataStore, -FilterStore, -
ContextStore, -SortingStore, -AggregationStore)
• components influence the store but also retrieved data
influences the store and therefore the components as
well.
benefits of refactoring to redux
• a single store made sense because all Components contributing to
one major backend call (getData and show in table)
• the stores state is now observed by Rx.Observable for changes and
a new backend call
• Better architecture with more dumb components which have the
properties injected instead of getting them from the store themselves.
• system feels more encapsulated with high cohesion (reducers and
one store) and looser coupling (killing the store calls in the
components)
• functional programming paradigms are enforced by design => easier
unit tests
boilerplate
• using https://github.com/erikras/react-redux-
universal-hot-example
• hooked in the boilerplate code as light as possible,
to pull changes from the original repository very
frequently.
• matter to drastically update in the future. Hourly
Changes are happening there.
references
http://rackt.org/redux/docs
Functional JavaScript
Michael Fogus O’Reilly 2013
Reactive Programming with JavaScript
Jonathan Hayward Packt 2015
https://github.com/xgrommx/awesome-redux
Ad

More Related Content

What's hot (20)

How to Redux
How to ReduxHow to Redux
How to Redux
Ted Pennings
 
React.js+Redux Workshops
React.js+Redux WorkshopsReact.js+Redux Workshops
React.js+Redux Workshops
Marcin Grzywaczewski
 
Redux Universal
Redux UniversalRedux Universal
Redux Universal
Nikolaus Graf
 
Angular redux
Angular reduxAngular redux
Angular redux
Nir Kaufman
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
Remo Jansen
 
React for Dummies
React for DummiesReact for Dummies
React for Dummies
Mitch Chen
 
Let's Redux!
Let's Redux!Let's Redux!
Let's Redux!
Joseph Chiang
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
Alex Bachuk
 
React js
React jsReact js
React js
Jai Santhosh
 
React / Redux Architectures
React / Redux ArchitecturesReact / Redux Architectures
React / Redux Architectures
Vinícius Ribeiro
 
Better web apps with React and Redux
Better web apps with React and ReduxBetter web apps with React and Redux
Better web apps with React and Redux
Ali Sa'o
 
Academy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & ToolingAcademy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & Tooling
Binary Studio
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
Vedran Blaženka
 
React, Flux and a little bit of Redux
React, Flux and a little bit of ReduxReact, Flux and a little bit of Redux
React, Flux and a little bit of Redux
Ny Fanilo Andrianjafy, B.Eng.
 
A Brief Introduction to React.js
A Brief Introduction to React.jsA Brief Introduction to React.js
A Brief Introduction to React.js
Doug Neiner
 
React and redux
React and reduxReact and redux
React and redux
Mystic Coders, LLC
 
Building Modern Web Applications using React and Redux
 Building Modern Web Applications using React and Redux Building Modern Web Applications using React and Redux
Building Modern Web Applications using React and Redux
Maxime Najim
 
The Road To Redux
The Road To ReduxThe Road To Redux
The Road To Redux
Jeffrey Sanchez
 
React & redux
React & reduxReact & redux
React & redux
Cédric Hartland
 
Introduction to React & Redux
Introduction to React & ReduxIntroduction to React & Redux
Introduction to React & Redux
Boris Dinkevich
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
Remo Jansen
 
React for Dummies
React for DummiesReact for Dummies
React for Dummies
Mitch Chen
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
Alex Bachuk
 
Better web apps with React and Redux
Better web apps with React and ReduxBetter web apps with React and Redux
Better web apps with React and Redux
Ali Sa'o
 
Academy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & ToolingAcademy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & Tooling
Binary Studio
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
Vedran Blaženka
 
A Brief Introduction to React.js
A Brief Introduction to React.jsA Brief Introduction to React.js
A Brief Introduction to React.js
Doug Neiner
 
Building Modern Web Applications using React and Redux
 Building Modern Web Applications using React and Redux Building Modern Web Applications using React and Redux
Building Modern Web Applications using React and Redux
Maxime Najim
 
Introduction to React & Redux
Introduction to React & ReduxIntroduction to React & Redux
Introduction to React & Redux
Boris Dinkevich
 

Viewers also liked (9)

React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
Nikolaus Graf
 
Redux and redux saga
Redux and redux sagaRedux and redux saga
Redux and redux saga
Jason Jae Yong An
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga begins
Daniel Franz
 
Getting Started with React-Nathan Smith
Getting Started with React-Nathan SmithGetting Started with React-Nathan Smith
Getting Started with React-Nathan Smith
TandemSeven
 
React & Redux
React & ReduxReact & Redux
React & Redux
Federico Bond
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJS
All Things Open
 
Linux Kernel Tour
Linux Kernel TourLinux Kernel Tour
Linux Kernel Tour
samrat das
 
React JS and why it's awesome
React JS and why it's awesomeReact JS and why it's awesome
React JS and why it's awesome
Andrew Hull
 
How to deploy PHP projects with docker
How to deploy PHP projects with dockerHow to deploy PHP projects with docker
How to deploy PHP projects with docker
Ruoshi Ling
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
Nikolaus Graf
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga begins
Daniel Franz
 
Getting Started with React-Nathan Smith
Getting Started with React-Nathan SmithGetting Started with React-Nathan Smith
Getting Started with React-Nathan Smith
TandemSeven
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJS
All Things Open
 
Linux Kernel Tour
Linux Kernel TourLinux Kernel Tour
Linux Kernel Tour
samrat das
 
React JS and why it's awesome
React JS and why it's awesomeReact JS and why it's awesome
React JS and why it's awesome
Andrew Hull
 
How to deploy PHP projects with docker
How to deploy PHP projects with dockerHow to deploy PHP projects with docker
How to deploy PHP projects with docker
Ruoshi Ling
 
Ad

Similar to Redux js (20)

Redux data flow with angular 2
Redux data flow with angular 2Redux data flow with angular 2
Redux data flow with angular 2
Gil Fink
 
Redux data flow with angular
Redux data flow with angularRedux data flow with angular
Redux data flow with angular
Gil Fink
 
Redux data flow with angular
Redux data flow with angularRedux data flow with angular
Redux data flow with angular
Gil Fink
 
Materi Modern React Redux Power Point.pdf
Materi Modern React Redux Power Point.pdfMateri Modern React Redux Power Point.pdf
Materi Modern React Redux Power Point.pdf
exiabreak
 
STATE MANAGEMENT IN REACT [Autosaved].pptx
STATE MANAGEMENT IN REACT [Autosaved].pptxSTATE MANAGEMENT IN REACT [Autosaved].pptx
STATE MANAGEMENT IN REACT [Autosaved].pptx
siddheshjadhav919123
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
洪 鹏发
 
Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016
Evan Schultz
 
Gabor Varadi - Reactive State Management with Jetpack Components
Gabor Varadi - Reactive State Management with Jetpack ComponentsGabor Varadi - Reactive State Management with Jetpack Components
Gabor Varadi - Reactive State Management with Jetpack Components
Gabor Varadi
 
Reactive state management with Jetpack Components
Reactive state management with Jetpack ComponentsReactive state management with Jetpack Components
Reactive state management with Jetpack Components
Gabor Varadi
 
Road to react hooks
Road to react hooksRoad to react hooks
Road to react hooks
Younes (omar) Meliani
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
DivyanshGupta922023
 
Introduction Web Development using ReactJS
Introduction Web Development using ReactJSIntroduction Web Development using ReactJS
Introduction Web Development using ReactJS
ssuser8a1f37
 
React JS Workings Exercises Extra Classes
React JS Workings Exercises Extra ClassesReact JS Workings Exercises Extra Classes
React JS Workings Exercises Extra Classes
ssuser426fcf
 
Redux Tech Talk
Redux Tech TalkRedux Tech Talk
Redux Tech Talk
Ashoka Chandra Wardhan
 
ReactJS
ReactJSReactJS
ReactJS
Kamlesh Singh
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тяга
Vitebsk Miniq
 
Spfx with react redux
Spfx with react reduxSpfx with react redux
Spfx with react redux
Rajesh Kumar
 
Workshop 22: React-Redux Middleware
Workshop 22: React-Redux MiddlewareWorkshop 22: React-Redux Middleware
Workshop 22: React-Redux Middleware
Visual Engineering
 
Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux Advanced
Visual Engineering
 
Making react part of something greater
Making react part of something greaterMaking react part of something greater
Making react part of something greater
Darko Kukovec
 
Redux data flow with angular 2
Redux data flow with angular 2Redux data flow with angular 2
Redux data flow with angular 2
Gil Fink
 
Redux data flow with angular
Redux data flow with angularRedux data flow with angular
Redux data flow with angular
Gil Fink
 
Redux data flow with angular
Redux data flow with angularRedux data flow with angular
Redux data flow with angular
Gil Fink
 
Materi Modern React Redux Power Point.pdf
Materi Modern React Redux Power Point.pdfMateri Modern React Redux Power Point.pdf
Materi Modern React Redux Power Point.pdf
exiabreak
 
STATE MANAGEMENT IN REACT [Autosaved].pptx
STATE MANAGEMENT IN REACT [Autosaved].pptxSTATE MANAGEMENT IN REACT [Autosaved].pptx
STATE MANAGEMENT IN REACT [Autosaved].pptx
siddheshjadhav919123
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
洪 鹏发
 
Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016
Evan Schultz
 
Gabor Varadi - Reactive State Management with Jetpack Components
Gabor Varadi - Reactive State Management with Jetpack ComponentsGabor Varadi - Reactive State Management with Jetpack Components
Gabor Varadi - Reactive State Management with Jetpack Components
Gabor Varadi
 
Reactive state management with Jetpack Components
Reactive state management with Jetpack ComponentsReactive state management with Jetpack Components
Reactive state management with Jetpack Components
Gabor Varadi
 
Introduction Web Development using ReactJS
Introduction Web Development using ReactJSIntroduction Web Development using ReactJS
Introduction Web Development using ReactJS
ssuser8a1f37
 
React JS Workings Exercises Extra Classes
React JS Workings Exercises Extra ClassesReact JS Workings Exercises Extra Classes
React JS Workings Exercises Extra Classes
ssuser426fcf
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тяга
Vitebsk Miniq
 
Spfx with react redux
Spfx with react reduxSpfx with react redux
Spfx with react redux
Rajesh Kumar
 
Workshop 22: React-Redux Middleware
Workshop 22: React-Redux MiddlewareWorkshop 22: React-Redux Middleware
Workshop 22: React-Redux Middleware
Visual Engineering
 
Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux Advanced
Visual Engineering
 
Making react part of something greater
Making react part of something greaterMaking react part of something greater
Making react part of something greater
Darko Kukovec
 
Ad

Recently uploaded (20)

SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 

Redux js

  • 1. Redux yet another flux implementation ? Nils Petersohn | twitter.com/snackycracky | [email protected]
  • 2. agenda • main ideas and overview of redux components • actions as pure functions • immutability and mutations in redux • sync flow • functional composition and redux middleware • async actions • reactjs bindings • experiences refactoring to redux
  • 3. what does it do ? • architecture to manage state • Redux attempts to make state mutations predictable by putting restrictions on how and when updates can happen. • does not attempt to solve the problems that Relay wants to solve • Relies heavily on functional programming paradigms
  • 4. ideas and components • Single source of truth • The state is stored in an object tree inside a single store. • State is read-only • The only way to mutate the state is to emit an action, an object describing what happened. • Mutations are written as pure functions • logic for changes triggered by those actions is inside “pure reducers”.
  • 5. pure functions • are encapsulated constructs with deterministic behaviour • trivial but predictable aka. easy testable • end up with hundreds of ever repeating arguments? • no, higher order functions and function compositions to the rescue
  • 6. redux-actions as pure functions • important difference to Flux: no dispatching inside the action • there is no Dispatcher at all; pure functions do not need to be managed, they need to be composed. //Action
 function addGoing(memberId){
 return { action: "ADD_GOING", memberId: memberId };
 }
  • 7. immutability • once “something” is created, it can’t be changed anymore • how to mutate then ? • make a new “something” with the desired changes • benefits ? • 100% sure that this “something” is not changed while being passed around in the flow. • don't have to worry about the underlying data being changed by another entity • (concurrency)
  • 8. reducers • invoked with current state and the desired actions as arguments to change the state create a new state • one store also means one reducer ? • no, there can be multiple reducers for the central store. Also reducers calling other reducers is common to modify deeply nested states. • redux will bind them together with `combineReducers(reducerList)` where each of them manages it’s own part of the global state
  • 9. example: List on meetup-page where people can RSVP
  • 10. immutability with reducers const initState = Immutable.Map({
 title: "", organiser: "", founded: "", going: [], notGoing: []
 })
 
 //reducer
 function reducingMeetupPage(state = initState, action){
 if(action.type == "ADD_GOING"){
 return state.update("going", (going) => going.add(action.memberId));
 }
 if(action.type == “ADD_NOT_GOING”){ 
 let clonedNotGoing = state.toJS().notGoing;
 clonedNotGoing.push(action.memberId); //ES6 spread syntax w/o ImmutableJS:
 return {...state.toJS(), notGoing: clonedNotGoing};
 }
 return state;
 }
 
 //Actions
 function addGoing(memberId){
 return { action: "ADD_GOING", memberId: memberId }; //pure: without dispatching
 }
 
 function addNotGoing(memberId){
 return { action: “ADD_NOT_GOING", memberId: memberId};
 }
  • 11. a smart react container • connects to everything redux. • actions and state are injected in the props • avoid rendering HTML, let the dumb components do that import {addGoing, addNotGoing} from "reducers/meetup"
 import {hideAlerts} from "reducers/users" 
 
 @connect(
 state => ({
 going: state.visibleMeetup.going,
 notGoing: state.visibleMeetup.notGoing,
 comments: state.visibleMeetup.comments,
 memberId: state.user.memberId,
 userAlerts: state.user.alerts
 }), 
 dispatch => bindActionCreators({
 addGoing, 
 addNotGoing, 
 hideAlerts}, dispatch)) 
 export default class MeetupPage extends Component {
 render() {
 const {going,notGoing,addGoing,addNotGoing,userAlerts,hideAlerts,memberId} = this.props;
 <div>
 <UserInfo userNotifications={userAlerts} hideAlerts={hideAlerts}/> 
 <AllOtherPageContent allOtherActions={...} />
 <GoingNotGoingComponent addGoing={addGoing} going={going} ... />
 </div>
 }
 }
  • 12. a dumb react component export default class GoingNotGoingComponent extends Component {
 render() {
 
 const {going, notGoing, memberId, addGoing, addNotGoing}= this.props;
 
 <div>
 <button onClick={addGoing.bind(null, memberId)}>I am Going</button>
 <ul className="going">
 {going.map(member => return <li>{member}</li>)}
 </ul>
 
 <hr/>
 
 <button onClick={addNotGoing.bind(null, memberId)}>I am NOT Going</button>
 <ul className="notGoing">
 {going.map(member => <li>{user}</li>)}
 </ul>
 </div>
 }
 } • does not know anything about redux. • actions and state are injected in the props … again • final payload is rendered here
  • 13. sync flow • Action -> Reducer -> SmartContainer -> DumbComponent ui smart Component injected state imported Action Objects wrapped with dispatch redux Action Objects / functions ReducerReducer Store dumb Component references to actions dumb Component references to actions
  • 14. function composition • currying = preconfigured functions being configured a little more http://stackoverflow.com/a/218055/170881 • checkout lodashs collection of higher order functions like _.compose, _.curry, _.partial
  • 15. middleware architecture with functional composition • It provides a third-party extension point between dispatching an action, and the moment it reaches the reducer. • People use Redux middleware for logging, crash reporting, talking to an asynchronous API, routing, and more. const logger = store => next => action => {
 console.log('dispatching', action);
 let result = next(action);
 console.log('next state', store.getState());
 return result;
 };
 
 let createStoreWithMiddleware = applyMiddleware(logger,...)(createStore);
 let myApp = combineReducers(reducers);
 let store = createStoreWithMiddleware(myApp);
  • 16. Async Actions• middleware can be used to check if the action contains promises and can execute them • In more complex apps you might want to use Rx for resolving async actions instead, and feed an observable of actions into Redux. export default function asyncActionsMiddleware(client) {
 return ({dispatch, getState}) => {
 return next => action => {
 const { promise, types, ...rest } = action; 
 if (!promise) {
 return next(action);
 }
 
 const [REQUEST, SUCCESS, FAILURE] = types;
 next({...rest, type: REQUEST});
 return promise(client).then(
 (result) => next({...rest, result, type: SUCCESS}),
 (error) => next({...rest, error, type: FAILURE})
 ).catch((error)=> {
 console.error('MIDDLEWARE ERROR:', error);
 next({...rest, error, type: FAILURE});
 });
 };
 };
 }

  • 17. one Async Flow = two Sync Flows redux Action Objects / functions ReducerReducer Store Middleware for API- Calls backend 1. request 1. disposing action for REQUESTING_DATA 2. response 2. disposing action for DATA_RECIEVED ui smart Component injected state imported Action Objects wrapped with dispatch dumb Component references to actions dumb Component references to actions 1. show spinner 2. show data API Endpoints
  • 18. react and flux inventory • 4 Views, 20 react-components and 12 stores. • one central view with a datagrid where data is shown • 6 stores in 3 views contribute to the datagrid's display properties: • UserRolesStore, datagrid(-DataStore, -FilterStore, - ContextStore, -SortingStore, -AggregationStore) • components influence the store but also retrieved data influences the store and therefore the components as well.
  • 19. benefits of refactoring to redux • a single store made sense because all Components contributing to one major backend call (getData and show in table) • the stores state is now observed by Rx.Observable for changes and a new backend call • Better architecture with more dumb components which have the properties injected instead of getting them from the store themselves. • system feels more encapsulated with high cohesion (reducers and one store) and looser coupling (killing the store calls in the components) • functional programming paradigms are enforced by design => easier unit tests
  • 20. boilerplate • using https://github.com/erikras/react-redux- universal-hot-example • hooked in the boilerplate code as light as possible, to pull changes from the original repository very frequently. • matter to drastically update in the future. Hourly Changes are happening there.
  • 21. references http://rackt.org/redux/docs Functional JavaScript Michael Fogus O’Reilly 2013 Reactive Programming with JavaScript Jonathan Hayward Packt 2015 https://github.com/xgrommx/awesome-redux