SlideShare a Scribd company logo
Building React Applications with Redux
Image by mulad
Many people choose to
think of React as the V in
MVC.
– “Why React?” in React documentation
“
MVC in Theory
Image by mulad
Model( ͡° ͜ʖ ͡°)
View
Controller
MVC in Practice
Image by mulad
View Model Model
Model
Model
Model
View Model
View Model
View Model ಠ_ಠ
Isolated (“Dumb”) Components
Parent
Child
Props Callbacks
Maximize your use of “dumb” components.
Advantages of Isolated Components
• Helps with code reuse.
• Helps with testing.
• Makes it easy to reason about your code.
Image by mulad
Sources of Those Benefits
• Dumb components are isolation from the rest of the
application.
• Dumb components are mostly stateless.
Image by mulad
Trouble with State
• A lot of us were raised on OOP. Objects are stateful.
• The effect of calling a method depends on the arguments and
the object’s state.
• Very painful to test.
• Very hard to understand.
• Aims to mimic the real world.
• But why replicate the unnecessary complexity?
Image by mulad
Alternative: Pure Functions
• The output of a pure function depends only on inputs.
• Pure function has no side-effects.
• Much easier to understand.
• Much easier to test.
• Very easy to build through composition.
Image by mulad
Truly Stateless Components
Image by mulad
function HelloMessage(props) {
return <div>Hello {props.name}</div>;
}
Even Better
Image by mulad
const HelloMessage = (props) => <div>Hello {props.name}</div>;
Use stateless components whenever you can.
Where Does Business Logic Go?
• Each component gets props from its parent.
• Each component transmits actions to the parent.
• Turtles all the way down up?
• Top-level components need to be a bit smarter!
• We’ll call them “container components”.
Image by mulad
Linking Containers with Models
Image by mulad
Container Model
ModelContainer
Nevermind…
Should We Use the Container’s State?
• We could, but so much for separation of concerns…
Image by mulad
What If We Did It the React Way?
???
Container Component
Props Callbacks
What If We Did It the React Way?
State Container
Container Component
Props Callbacks
Flux Architecture
State Container
Container Component
Change events Actions
Handling Data in the State Container
Component
StoreComponent
Dispatcher
Action
Handling Data in the State Container
Component
Store
API, etc.
Component
Dispatcher
Action(s)Action

Creator
We’ll see another

way of doing this.
Redux
A Better State Container
• https://github.com/rackt/redux
• Pretty much the dominant way of doing Flux with React
today.
• Key concepts: a single store + state “reducers”.
• Can a single store be a good idea?
• What the heck is a “reducer”?
Reducer Functions
• Basic reduce():
function addOneValue (value, state) {
return state + value;
}
[1,2,3,4,5].reduce(addOneValue, 0);
• Running through the items:
1: 0 => 1
2: 1 => 3
3: 3 => 6
4: 6 => 10
5: 10 => 15
Action Reducers in Redux
• Take an action and a state, return a new state.
• Your app’s state is a reduction over the actions.
• Each reducer operates on a subset of the global state.
• Simple reducers are combined into complex ones.
Creating an Action
const UPDATE_NOTE_CONTENT = 'App/UPDATE_NOTE_CONTENT';
function updateNoteContent(noteId, newContent) {
return {
type: UPDATE_NOTE_CONTENT,
payload: {
noteId: noteId,
newContent: newContent
}
}
}
Creating an Action, more ES6
const UPDATE_NOTE_CONTENT = 'App/UPDATE_NOTE_CONTENT';
const updateNoteContent = (noteId, newContent) => ({
type: UPDATE_NOTE_CONTENT,
payload: {noteId, newContent}
});
A Reducer
export const notes = createReducer({
[UPDATE_NOTE_CONTENT]: (state, action) => state.setIn(
['byId', action.payload.noteId, 'html'],
action.payload.newContent
),
[SOME_OTHER_ACTION]: (state, action) => {
// do something else or just
return state;
}),
});
A Reducer, more ES5ish
export const notes = createReducer({
[UPDATE_NOTE_CONTENT]: function (state, action) {
return state.setIn(
['byId', action.payload.noteId, 'html'],
action.payload.newContent
);
},
[SOME_OTHER_ACTION]: function (state, action) {
// do something else or just
return state;
},
});
Why Is This a Good Idea?
• Reducers are pure functions – easy to understand, easy to
test.
• Reducers are synchronous.
• Data logic is 100% separated from view logic.
• You can still have modularity by combining reducers.
• New opportunities for tools.
How Do We Avoid Mutating State?
• Reducers are supposed to not change the old state. But how
do we keep them honest?
• One option is to clone the object every time.
• “Immutable.JS” is the library to use.
var newData = data.setIn(
['foo', 'bar', 'baz'],
42
);
• This is a key building block for stateless architecture.
The Reducer Example Again
export const notes = createReducer({
[UPDATE_NOTE_CONTENT]: (state, action) => state.setIn(
['byId', action.payload.noteId, 'html'],
action.payload.newContent
),
[SOME_OTHER_ACTION]: (state, action) => {
// do something else or just
return state;
}),
});
Connecting Container Components
import { connect } from 'react-redux';
export default connect(
mapStateToProps,
mapDispatchToProps,
)(MainPage);
React-Redux Mapping Functions
function mapStateToProps(state) {
const notesAsJS = state.notes.toJS();
return {
notes: notesAsJS.ordered.map((id) => notesAsJS.byId[id])
};
}
function mapDispatchToProps(dispatch) {
return {
onContentChange: (noteId, newContent) =>
dispatch(noteActions.updateNoteContent(
noteId, newContent)),
};
}
Handling Asyncronous Actions
• Option 1: “Smart” actions creators.
• Option 2: Middleware.
• Option 2′: React Sagas.
Smart Action Creators
• Call an action creator to initiate a request.
• The action creator emits an action to inform everyone that a
request was made.
• The action creator makes a request.
• If the request succeeds, the action creator emits an action to
inform everyone that a request was completed. (Same for
failure and timeout.)
• The details of interacting with the server should be pushed
into a module.
An Example, Part 1
function makeFetchNotesAction(status, data) {
return {
type: FETCH_NOTES,
payload: {
status: status,
data: data
}
};
}
An Example, Part 1
export function fetchNotes() {
return dispatch => {
dispatch(makeFetchNotesAction('request'));
return fetchData()
.then(json => dispatch(makeFetchNotesAction('success', json)))
.catch(error => dispatch(makeFetchNotesAction('error', error)));
};
}
Alternatively: Redux Middleware
• A middleware is a function that allows you to capture actions
and do something before they get to the reducers.
• This can include things like API calls.
• More generally, the sky is the limit.
• Perhaps a little too generic for many cases.
Alternative: Redux Sagas
• A middleware that works with generators.
• Awesome, if you understand generators.
• Can simplify complex workflows.
• Very new.
Redux Sagas Example
function* fetchNotesForStack(action) {
const stackId = action.payload.stackId;
yield put(getNotes.request());
const {data, error} = yield dataApi.getNotesForStack(stackId);
if (!error) {
yield put(getNotes.success(organizeNotes(data.notes)));
} else {
yield put(getNotes.failure(error));
}
}
function* watchFetchNotesForStack() {
yield* takeEvery(SELECT_STACK, fetchNotesForStack);
}
Testing Is Easy
describe('on ADD_NOTE', () => {
it('should create a new note', () => {
const getNoteCount = () => initialState.toJS().ordered.length;
const previousCount = getNoteCount();
const newState = notesReducer(initialState, {type: ADD_NOTE});
assert.strictEqual(previousCount + 1, getNoteCount());
const newNoteId = newState.toJS().ordered[0];
const newNoteHtml = newState.getIn(['byId', newNoteId, 'html']);
assert.strictEqual(newNoteHtml, 'No content');
});
});
Caveats
• Its addictive.
• You won’t be happy using anything else.
• Your friends might not understand your obsession.
THANK YOU!
Yuri Takhteyev
@qaramazov
rangle
CTO, Rangle.io
Some rights reserved - Creative Commons 2.0 by-sa

More Related Content

What's hot (20)

Designing applications with Redux
Designing applications with ReduxDesigning applications with Redux
Designing applications with Redux
Fernando Daciuk
 
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
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJS
All Things Open
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
Ignacio Martín
 
Getting started with Redux js
Getting started with Redux jsGetting started with Redux js
Getting started with Redux js
Citrix
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
Alex Bachuk
 
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.
 
Angular redux
Angular reduxAngular redux
Angular redux
Nir Kaufman
 
React js
React jsReact js
React js
Jai Santhosh
 
React redux
React reduxReact redux
React redux
Michel Perez
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
Vedran Blaženka
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practices
Clickky
 
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 / Redux Architectures
React / Redux ArchitecturesReact / Redux Architectures
React / Redux Architectures
Vinícius Ribeiro
 
Using redux
Using reduxUsing redux
Using redux
Jonas Ohlsson Aden
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
Nikolaus Graf
 
Redux training
Redux trainingRedux training
Redux training
dasersoft
 
Introduction to React & Redux
Introduction to React & ReduxIntroduction to React & Redux
Introduction to React & Redux
Boris Dinkevich
 
Introduction to react and redux
Introduction to react and reduxIntroduction to react and redux
Introduction to react and redux
Cuong Ho
 
Designing applications with Redux
Designing applications with ReduxDesigning applications with Redux
Designing applications with Redux
Fernando Daciuk
 
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
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJS
All Things Open
 
Getting started with Redux js
Getting started with Redux jsGetting started with Redux js
Getting started with Redux js
Citrix
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
Alex Bachuk
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
Vedran Blaženka
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practices
Clickky
 
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 + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
Nikolaus Graf
 
Redux training
Redux trainingRedux training
Redux training
dasersoft
 
Introduction to React & Redux
Introduction to React & ReduxIntroduction to React & Redux
Introduction to React & Redux
Boris Dinkevich
 
Introduction to react and redux
Introduction to react and reduxIntroduction to react and redux
Introduction to react and redux
Cuong Ho
 

Viewers also liked (20)

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
 
React.js in real world apps.
React.js in real world apps. React.js in real world apps.
React.js in real world apps.
Emanuele DelBono
 
How to Redux
How to ReduxHow to Redux
How to Redux
Ted Pennings
 
Robust web apps with React.js
Robust web apps with React.jsRobust web apps with React.js
Robust web apps with React.js
Max Klymyshyn
 
Flux and redux
Flux and reduxFlux and redux
Flux and redux
Morgan Cheng
 
Reducers+flux=redux
Reducers+flux=reduxReducers+flux=redux
Reducers+flux=redux
Shmulik Chicvashvili
 
React&redux
React&reduxReact&redux
React&redux
Blank Chen
 
Redux vs Alt
Redux vs AltRedux vs Alt
Redux vs Alt
Uldis Sturms
 
Angular js com diretivas
Angular js com diretivasAngular js com diretivas
Angular js com diretivas
Matheus Lima
 
Apresentação AngularJS - Angular UI
Apresentação AngularJS - Angular UIApresentação AngularJS - Angular UI
Apresentação AngularJS - Angular UI
Cecília Rosa
 
An Intense Overview of the React Ecosystem
An Intense Overview of the React EcosystemAn Intense Overview of the React Ecosystem
An Intense Overview of the React Ecosystem
Rami Sayar
 
React, Flux y React native
React, Flux y React nativeReact, Flux y React native
React, Flux y React native
Eduard Tomàs
 
React – ¿Qué es React.js?
React – ¿Qué es React.js?React – ¿Qué es React.js?
React – ¿Qué es React.js?
Gorka Magaña
 
JSConf US 2014: Building Isomorphic Apps
JSConf US 2014: Building Isomorphic AppsJSConf US 2014: Building Isomorphic Apps
JSConf US 2014: Building Isomorphic Apps
Spike Brehm
 
Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.
Astrails
 
React. Flux. Redux
React. Flux. ReduxReact. Flux. Redux
React. Flux. Redux
Andrey Kolodnitsky
 
Soa Fundamentos
Soa FundamentosSoa Fundamentos
Soa Fundamentos
Rildo (@rildosan) Santos
 
Arquitetura Orientada a Servicos (SOA)
Arquitetura Orientada a Servicos (SOA)Arquitetura Orientada a Servicos (SOA)
Arquitetura Orientada a Servicos (SOA)
Marcelo Sávio
 
Angular js
Angular jsAngular js
Angular js
Bruno Catão
 
Criando serviços com AngularJS
Criando serviços com AngularJSCriando serviços com AngularJS
Criando serviços com AngularJS
Rodrigo Branas
 
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
 
React.js in real world apps.
React.js in real world apps. React.js in real world apps.
React.js in real world apps.
Emanuele DelBono
 
Robust web apps with React.js
Robust web apps with React.jsRobust web apps with React.js
Robust web apps with React.js
Max Klymyshyn
 
Angular js com diretivas
Angular js com diretivasAngular js com diretivas
Angular js com diretivas
Matheus Lima
 
Apresentação AngularJS - Angular UI
Apresentação AngularJS - Angular UIApresentação AngularJS - Angular UI
Apresentação AngularJS - Angular UI
Cecília Rosa
 
An Intense Overview of the React Ecosystem
An Intense Overview of the React EcosystemAn Intense Overview of the React Ecosystem
An Intense Overview of the React Ecosystem
Rami Sayar
 
React, Flux y React native
React, Flux y React nativeReact, Flux y React native
React, Flux y React native
Eduard Tomàs
 
React – ¿Qué es React.js?
React – ¿Qué es React.js?React – ¿Qué es React.js?
React – ¿Qué es React.js?
Gorka Magaña
 
JSConf US 2014: Building Isomorphic Apps
JSConf US 2014: Building Isomorphic AppsJSConf US 2014: Building Isomorphic Apps
JSConf US 2014: Building Isomorphic Apps
Spike Brehm
 
Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.
Astrails
 
Arquitetura Orientada a Servicos (SOA)
Arquitetura Orientada a Servicos (SOA)Arquitetura Orientada a Servicos (SOA)
Arquitetura Orientada a Servicos (SOA)
Marcelo Sávio
 
Criando serviços com AngularJS
Criando serviços com AngularJSCriando serviços com AngularJS
Criando serviços com AngularJS
Rodrigo Branas
 
Ad

Similar to Building React Applications with Redux (20)

Redux essentials
Redux essentialsRedux essentials
Redux essentials
Chandan Kumar Rana
 
Maintaining sanity in a large redux app
Maintaining sanity in a large redux appMaintaining sanity in a large redux app
Maintaining sanity in a large redux app
Nitish Kumar
 
Redux
ReduxRedux
Redux
Maulik Shah
 
Understanding redux
Understanding reduxUnderstanding redux
Understanding redux
David Atchley
 
React.js at Cortex
React.js at CortexReact.js at Cortex
React.js at Cortex
Geoff Harcourt
 
Getting started with React and Redux
Getting started with React and ReduxGetting started with React and Redux
Getting started with React and Redux
Paddy Lock
 
[@NaukriEngineering] Flux Architecture
[@NaukriEngineering] Flux Architecture[@NaukriEngineering] Flux Architecture
[@NaukriEngineering] Flux Architecture
Naukri.com
 
Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016
Evan Schultz
 
Redux workshop
Redux workshopRedux workshop
Redux workshop
Imran Sayed
 
React & redux
React & reduxReact & redux
React & redux
Cédric Hartland
 
React + Flux = Joy
React + Flux = JoyReact + Flux = Joy
React + Flux = Joy
John Need
 
React/Redux
React/ReduxReact/Redux
React/Redux
Durgesh Vaishnav
 
ReactRedux.pdf
ReactRedux.pdfReactRedux.pdf
ReactRedux.pdf
Arsalan malik
 
React Interview Question & Answers PDF By ScholarHat
React Interview Question & Answers PDF By ScholarHatReact Interview Question & Answers PDF By ScholarHat
React Interview Question & Answers PDF By ScholarHat
Scholarhat
 
an Introduction to Redux
an Introduction to Reduxan Introduction to Redux
an Introduction to Redux
Amin Ashtiani
 
A React Journey
A React JourneyA React Journey
A React Journey
LinkMe Srl
 
React and redux
React and reduxReact and redux
React and redux
Mystic Coders, LLC
 
Manage the Flux of your Web Application: Let's Redux
Manage the Flux of your Web Application: Let's ReduxManage the Flux of your Web Application: Let's Redux
Manage the Flux of your Web Application: Let's Redux
Commit University
 
Content-Driven Apps with React
Content-Driven Apps with ReactContent-Driven Apps with React
Content-Driven Apps with React
Netcetera
 
Redux Tech Talk
Redux Tech TalkRedux Tech Talk
Redux Tech Talk
Chathuranga Jayanath
 
Maintaining sanity in a large redux app
Maintaining sanity in a large redux appMaintaining sanity in a large redux app
Maintaining sanity in a large redux app
Nitish Kumar
 
Getting started with React and Redux
Getting started with React and ReduxGetting started with React and Redux
Getting started with React and Redux
Paddy Lock
 
[@NaukriEngineering] Flux Architecture
[@NaukriEngineering] Flux Architecture[@NaukriEngineering] Flux Architecture
[@NaukriEngineering] Flux Architecture
Naukri.com
 
Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016Evan Schultz - Angular Summit - 2016
Evan Schultz - Angular Summit - 2016
Evan Schultz
 
React + Flux = Joy
React + Flux = JoyReact + Flux = Joy
React + Flux = Joy
John Need
 
React Interview Question & Answers PDF By ScholarHat
React Interview Question & Answers PDF By ScholarHatReact Interview Question & Answers PDF By ScholarHat
React Interview Question & Answers PDF By ScholarHat
Scholarhat
 
an Introduction to Redux
an Introduction to Reduxan Introduction to Redux
an Introduction to Redux
Amin Ashtiani
 
A React Journey
A React JourneyA React Journey
A React Journey
LinkMe Srl
 
Manage the Flux of your Web Application: Let's Redux
Manage the Flux of your Web Application: Let's ReduxManage the Flux of your Web Application: Let's Redux
Manage the Flux of your Web Application: Let's Redux
Commit University
 
Content-Driven Apps with React
Content-Driven Apps with ReactContent-Driven Apps with React
Content-Driven Apps with React
Netcetera
 
Ad

More from FITC (20)

Cut it up
Cut it upCut it up
Cut it up
FITC
 
Designing for Digital Health
Designing for Digital HealthDesigning for Digital Health
Designing for Digital Health
FITC
 
Profiling JavaScript Performance
Profiling JavaScript PerformanceProfiling JavaScript Performance
Profiling JavaScript Performance
FITC
 
Surviving Your Tech Stack
Surviving Your Tech StackSurviving Your Tech Stack
Surviving Your Tech Stack
FITC
 
How to Pitch Your First AR Project
How to Pitch Your First AR ProjectHow to Pitch Your First AR Project
How to Pitch Your First AR Project
FITC
 
Start by Understanding the Problem, Not by Delivering the Answer
Start by Understanding the Problem, Not by Delivering the AnswerStart by Understanding the Problem, Not by Delivering the Answer
Start by Understanding the Problem, Not by Delivering the Answer
FITC
 
Cocaine to Carrots: The Art of Telling Someone Else’s Story
Cocaine to Carrots: The Art of Telling Someone Else’s StoryCocaine to Carrots: The Art of Telling Someone Else’s Story
Cocaine to Carrots: The Art of Telling Someone Else’s Story
FITC
 
Everyday Innovation
Everyday InnovationEveryday Innovation
Everyday Innovation
FITC
 
HyperLight Websites
HyperLight WebsitesHyperLight Websites
HyperLight Websites
FITC
 
Everything is Terrifying
Everything is TerrifyingEverything is Terrifying
Everything is Terrifying
FITC
 
Post-Earth Visions: Designing for Space and the Future Human
Post-Earth Visions: Designing for Space and the Future HumanPost-Earth Visions: Designing for Space and the Future Human
Post-Earth Visions: Designing for Space and the Future Human
FITC
 
The Rise of the Creative Social Influencer (and How to Become One)
The Rise of the Creative Social Influencer (and How to Become One)The Rise of the Creative Social Influencer (and How to Become One)
The Rise of the Creative Social Influencer (and How to Become One)
FITC
 
East of the Rockies: Developing an AR Game
East of the Rockies: Developing an AR GameEast of the Rockies: Developing an AR Game
East of the Rockies: Developing an AR Game
FITC
 
Creating a Proactive Healthcare System
Creating a Proactive Healthcare SystemCreating a Proactive Healthcare System
Creating a Proactive Healthcare System
FITC
 
World Transformation: The Secret Agenda of Product Design
World Transformation: The Secret Agenda of Product DesignWorld Transformation: The Secret Agenda of Product Design
World Transformation: The Secret Agenda of Product Design
FITC
 
The Power of Now
The Power of NowThe Power of Now
The Power of Now
FITC
 
High Performance PWAs
High Performance PWAsHigh Performance PWAs
High Performance PWAs
FITC
 
Rise of the JAMstack
Rise of the JAMstackRise of the JAMstack
Rise of the JAMstack
FITC
 
From Closed to Open: A Journey of Self Discovery
From Closed to Open: A Journey of Self DiscoveryFrom Closed to Open: A Journey of Self Discovery
From Closed to Open: A Journey of Self Discovery
FITC
 
Projects Ain’t Nobody Got Time For
Projects Ain’t Nobody Got Time ForProjects Ain’t Nobody Got Time For
Projects Ain’t Nobody Got Time For
FITC
 
Cut it up
Cut it upCut it up
Cut it up
FITC
 
Designing for Digital Health
Designing for Digital HealthDesigning for Digital Health
Designing for Digital Health
FITC
 
Profiling JavaScript Performance
Profiling JavaScript PerformanceProfiling JavaScript Performance
Profiling JavaScript Performance
FITC
 
Surviving Your Tech Stack
Surviving Your Tech StackSurviving Your Tech Stack
Surviving Your Tech Stack
FITC
 
How to Pitch Your First AR Project
How to Pitch Your First AR ProjectHow to Pitch Your First AR Project
How to Pitch Your First AR Project
FITC
 
Start by Understanding the Problem, Not by Delivering the Answer
Start by Understanding the Problem, Not by Delivering the AnswerStart by Understanding the Problem, Not by Delivering the Answer
Start by Understanding the Problem, Not by Delivering the Answer
FITC
 
Cocaine to Carrots: The Art of Telling Someone Else’s Story
Cocaine to Carrots: The Art of Telling Someone Else’s StoryCocaine to Carrots: The Art of Telling Someone Else’s Story
Cocaine to Carrots: The Art of Telling Someone Else’s Story
FITC
 
Everyday Innovation
Everyday InnovationEveryday Innovation
Everyday Innovation
FITC
 
HyperLight Websites
HyperLight WebsitesHyperLight Websites
HyperLight Websites
FITC
 
Everything is Terrifying
Everything is TerrifyingEverything is Terrifying
Everything is Terrifying
FITC
 
Post-Earth Visions: Designing for Space and the Future Human
Post-Earth Visions: Designing for Space and the Future HumanPost-Earth Visions: Designing for Space and the Future Human
Post-Earth Visions: Designing for Space and the Future Human
FITC
 
The Rise of the Creative Social Influencer (and How to Become One)
The Rise of the Creative Social Influencer (and How to Become One)The Rise of the Creative Social Influencer (and How to Become One)
The Rise of the Creative Social Influencer (and How to Become One)
FITC
 
East of the Rockies: Developing an AR Game
East of the Rockies: Developing an AR GameEast of the Rockies: Developing an AR Game
East of the Rockies: Developing an AR Game
FITC
 
Creating a Proactive Healthcare System
Creating a Proactive Healthcare SystemCreating a Proactive Healthcare System
Creating a Proactive Healthcare System
FITC
 
World Transformation: The Secret Agenda of Product Design
World Transformation: The Secret Agenda of Product DesignWorld Transformation: The Secret Agenda of Product Design
World Transformation: The Secret Agenda of Product Design
FITC
 
The Power of Now
The Power of NowThe Power of Now
The Power of Now
FITC
 
High Performance PWAs
High Performance PWAsHigh Performance PWAs
High Performance PWAs
FITC
 
Rise of the JAMstack
Rise of the JAMstackRise of the JAMstack
Rise of the JAMstack
FITC
 
From Closed to Open: A Journey of Self Discovery
From Closed to Open: A Journey of Self DiscoveryFrom Closed to Open: A Journey of Self Discovery
From Closed to Open: A Journey of Self Discovery
FITC
 
Projects Ain’t Nobody Got Time For
Projects Ain’t Nobody Got Time ForProjects Ain’t Nobody Got Time For
Projects Ain’t Nobody Got Time For
FITC
 

Recently uploaded (20)

UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animationUV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
17218
 
What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
CartCoders
 
The it.com Domains Brand Book for registrars, domain resellers and hosting co...
The it.com Domains Brand Book for registrars, domain resellers and hosting co...The it.com Domains Brand Book for registrars, domain resellers and hosting co...
The it.com Domains Brand Book for registrars, domain resellers and hosting co...
it.com Domains
 
Darley - BSides Nairobi (2025-06-07) Epochalypse 2038 - Time is Not on Our Si...
Darley - BSides Nairobi (2025-06-07) Epochalypse 2038 - Time is Not on Our Si...Darley - BSides Nairobi (2025-06-07) Epochalypse 2038 - Time is Not on Our Si...
Darley - BSides Nairobi (2025-06-07) Epochalypse 2038 - Time is Not on Our Si...
treyka
 
simple-presentationtestingdocument2007.pptx
simple-presentationtestingdocument2007.pptxsimple-presentationtestingdocument2007.pptx
simple-presentationtestingdocument2007.pptx
ashokjayapal
 
最新版美国威斯康星大学绿湾分校毕业证(UWGB毕业证书)原版定制
最新版美国威斯康星大学绿湾分校毕业证(UWGB毕业证书)原版定制最新版美国威斯康星大学绿湾分校毕业证(UWGB毕业证书)原版定制
最新版美国威斯康星大学绿湾分校毕业证(UWGB毕业证书)原版定制
Taqyea
 
Vigilanti-Cura-Protecting-the-Faith.pptx
Vigilanti-Cura-Protecting-the-Faith.pptxVigilanti-Cura-Protecting-the-Faith.pptx
Vigilanti-Cura-Protecting-the-Faith.pptx
secretarysocom
 
DDos Mitigation Strategie, presented at bdNOG 19
DDos Mitigation Strategie, presented at bdNOG 19DDos Mitigation Strategie, presented at bdNOG 19
DDos Mitigation Strategie, presented at bdNOG 19
APNIC
 
3 years of Quarkus in production, what have we learned - Devoxx Polen
3 years of Quarkus in production, what have we learned - Devoxx Polen3 years of Quarkus in production, what have we learned - Devoxx Polen
3 years of Quarkus in production, what have we learned - Devoxx Polen
Jago de Vreede
 
Quantiuwewe e3er14e we3223 32222 m2.pptx
Quantiuwewe e3er14e we3223 32222 m2.pptxQuantiuwewe e3er14e we3223 32222 m2.pptx
Quantiuwewe e3er14e we3223 32222 m2.pptx
cyberesearchprof
 
Cloud Computing - iCloud by Hamza Anwaar .pptx
Cloud Computing - iCloud by Hamza Anwaar .pptxCloud Computing - iCloud by Hamza Anwaar .pptx
Cloud Computing - iCloud by Hamza Anwaar .pptx
islamicknowledge5224
 
MOBILE PHONE DATA presentation with all necessary details
MOBILE PHONE DATA presentation with all necessary detailsMOBILE PHONE DATA presentation with all necessary details
MOBILE PHONE DATA presentation with all necessary details
benamorraj
 
rosoft PowcgnggerPoint Presentation.pptx
rosoft PowcgnggerPoint Presentation.pptxrosoft PowcgnggerPoint Presentation.pptx
rosoft PowcgnggerPoint Presentation.pptx
sirbabu778
 
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdfPredicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Behzad Hussain
 
In order to install and use the device software, your computer must meet the ...
In order to install and use the device software, your computer must meet the ...In order to install and use the device software, your computer must meet the ...
In order to install and use the device software, your computer must meet the ...
raguclc
 
Internet_of_Things_Presentation_by-Humera.pptx
Internet_of_Things_Presentation_by-Humera.pptxInternet_of_Things_Presentation_by-Humera.pptx
Internet_of_Things_Presentation_by-Humera.pptx
cshumerabashir
 
AI theory work for students to understand the logic
AI theory work for students to understand the logicAI theory work for students to understand the logic
AI theory work for students to understand the logic
areeba15775n
 
Internet & Protocols : A Blueprint of the Internet System
Internet & Protocols : A Blueprint of the Internet SystemInternet & Protocols : A Blueprint of the Internet System
Internet & Protocols : A Blueprint of the Internet System
cpnabil59
 
PPT 18.03.2023.pptx for i smart programme
PPT 18.03.2023.pptx for i smart programmePPT 18.03.2023.pptx for i smart programme
PPT 18.03.2023.pptx for i smart programme
AbhimanShastry
 
最新版西班牙加泰罗尼亚国际大学毕业证(UIC毕业证书)原版定制
最新版西班牙加泰罗尼亚国际大学毕业证(UIC毕业证书)原版定制最新版西班牙加泰罗尼亚国际大学毕业证(UIC毕业证书)原版定制
最新版西班牙加泰罗尼亚国际大学毕业证(UIC毕业证书)原版定制
Taqyea
 
UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animationUV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
17218
 
What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
CartCoders
 
The it.com Domains Brand Book for registrars, domain resellers and hosting co...
The it.com Domains Brand Book for registrars, domain resellers and hosting co...The it.com Domains Brand Book for registrars, domain resellers and hosting co...
The it.com Domains Brand Book for registrars, domain resellers and hosting co...
it.com Domains
 
Darley - BSides Nairobi (2025-06-07) Epochalypse 2038 - Time is Not on Our Si...
Darley - BSides Nairobi (2025-06-07) Epochalypse 2038 - Time is Not on Our Si...Darley - BSides Nairobi (2025-06-07) Epochalypse 2038 - Time is Not on Our Si...
Darley - BSides Nairobi (2025-06-07) Epochalypse 2038 - Time is Not on Our Si...
treyka
 
simple-presentationtestingdocument2007.pptx
simple-presentationtestingdocument2007.pptxsimple-presentationtestingdocument2007.pptx
simple-presentationtestingdocument2007.pptx
ashokjayapal
 
最新版美国威斯康星大学绿湾分校毕业证(UWGB毕业证书)原版定制
最新版美国威斯康星大学绿湾分校毕业证(UWGB毕业证书)原版定制最新版美国威斯康星大学绿湾分校毕业证(UWGB毕业证书)原版定制
最新版美国威斯康星大学绿湾分校毕业证(UWGB毕业证书)原版定制
Taqyea
 
Vigilanti-Cura-Protecting-the-Faith.pptx
Vigilanti-Cura-Protecting-the-Faith.pptxVigilanti-Cura-Protecting-the-Faith.pptx
Vigilanti-Cura-Protecting-the-Faith.pptx
secretarysocom
 
DDos Mitigation Strategie, presented at bdNOG 19
DDos Mitigation Strategie, presented at bdNOG 19DDos Mitigation Strategie, presented at bdNOG 19
DDos Mitigation Strategie, presented at bdNOG 19
APNIC
 
3 years of Quarkus in production, what have we learned - Devoxx Polen
3 years of Quarkus in production, what have we learned - Devoxx Polen3 years of Quarkus in production, what have we learned - Devoxx Polen
3 years of Quarkus in production, what have we learned - Devoxx Polen
Jago de Vreede
 
Quantiuwewe e3er14e we3223 32222 m2.pptx
Quantiuwewe e3er14e we3223 32222 m2.pptxQuantiuwewe e3er14e we3223 32222 m2.pptx
Quantiuwewe e3er14e we3223 32222 m2.pptx
cyberesearchprof
 
Cloud Computing - iCloud by Hamza Anwaar .pptx
Cloud Computing - iCloud by Hamza Anwaar .pptxCloud Computing - iCloud by Hamza Anwaar .pptx
Cloud Computing - iCloud by Hamza Anwaar .pptx
islamicknowledge5224
 
MOBILE PHONE DATA presentation with all necessary details
MOBILE PHONE DATA presentation with all necessary detailsMOBILE PHONE DATA presentation with all necessary details
MOBILE PHONE DATA presentation with all necessary details
benamorraj
 
rosoft PowcgnggerPoint Presentation.pptx
rosoft PowcgnggerPoint Presentation.pptxrosoft PowcgnggerPoint Presentation.pptx
rosoft PowcgnggerPoint Presentation.pptx
sirbabu778
 
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdfPredicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Behzad Hussain
 
In order to install and use the device software, your computer must meet the ...
In order to install and use the device software, your computer must meet the ...In order to install and use the device software, your computer must meet the ...
In order to install and use the device software, your computer must meet the ...
raguclc
 
Internet_of_Things_Presentation_by-Humera.pptx
Internet_of_Things_Presentation_by-Humera.pptxInternet_of_Things_Presentation_by-Humera.pptx
Internet_of_Things_Presentation_by-Humera.pptx
cshumerabashir
 
AI theory work for students to understand the logic
AI theory work for students to understand the logicAI theory work for students to understand the logic
AI theory work for students to understand the logic
areeba15775n
 
Internet & Protocols : A Blueprint of the Internet System
Internet & Protocols : A Blueprint of the Internet SystemInternet & Protocols : A Blueprint of the Internet System
Internet & Protocols : A Blueprint of the Internet System
cpnabil59
 
PPT 18.03.2023.pptx for i smart programme
PPT 18.03.2023.pptx for i smart programmePPT 18.03.2023.pptx for i smart programme
PPT 18.03.2023.pptx for i smart programme
AbhimanShastry
 
最新版西班牙加泰罗尼亚国际大学毕业证(UIC毕业证书)原版定制
最新版西班牙加泰罗尼亚国际大学毕业证(UIC毕业证书)原版定制最新版西班牙加泰罗尼亚国际大学毕业证(UIC毕业证书)原版定制
最新版西班牙加泰罗尼亚国际大学毕业证(UIC毕业证书)原版定制
Taqyea
 

Building React Applications with Redux

  • 2. Image by mulad Many people choose to think of React as the V in MVC. – “Why React?” in React documentation “
  • 3. MVC in Theory Image by mulad Model( ͡° ͜ʖ ͡°) View Controller
  • 4. MVC in Practice Image by mulad View Model Model Model Model Model View Model View Model View Model ಠ_ಠ
  • 5. Isolated (“Dumb”) Components Parent Child Props Callbacks Maximize your use of “dumb” components.
  • 6. Advantages of Isolated Components • Helps with code reuse. • Helps with testing. • Makes it easy to reason about your code. Image by mulad
  • 7. Sources of Those Benefits • Dumb components are isolation from the rest of the application. • Dumb components are mostly stateless. Image by mulad
  • 8. Trouble with State • A lot of us were raised on OOP. Objects are stateful. • The effect of calling a method depends on the arguments and the object’s state. • Very painful to test. • Very hard to understand. • Aims to mimic the real world. • But why replicate the unnecessary complexity? Image by mulad
  • 9. Alternative: Pure Functions • The output of a pure function depends only on inputs. • Pure function has no side-effects. • Much easier to understand. • Much easier to test. • Very easy to build through composition. Image by mulad
  • 10. Truly Stateless Components Image by mulad function HelloMessage(props) { return <div>Hello {props.name}</div>; }
  • 11. Even Better Image by mulad const HelloMessage = (props) => <div>Hello {props.name}</div>; Use stateless components whenever you can.
  • 12. Where Does Business Logic Go? • Each component gets props from its parent. • Each component transmits actions to the parent. • Turtles all the way down up? • Top-level components need to be a bit smarter! • We’ll call them “container components”. Image by mulad
  • 13. Linking Containers with Models Image by mulad Container Model ModelContainer Nevermind…
  • 14. Should We Use the Container’s State? • We could, but so much for separation of concerns… Image by mulad
  • 15. What If We Did It the React Way? ??? Container Component Props Callbacks
  • 16. What If We Did It the React Way? State Container Container Component Props Callbacks
  • 17. Flux Architecture State Container Container Component Change events Actions
  • 18. Handling Data in the State Container Component StoreComponent Dispatcher Action
  • 19. Handling Data in the State Container Component Store API, etc. Component Dispatcher Action(s)Action
 Creator We’ll see another
 way of doing this.
  • 20. Redux
  • 21. A Better State Container • https://github.com/rackt/redux • Pretty much the dominant way of doing Flux with React today. • Key concepts: a single store + state “reducers”. • Can a single store be a good idea? • What the heck is a “reducer”?
  • 22. Reducer Functions • Basic reduce(): function addOneValue (value, state) { return state + value; } [1,2,3,4,5].reduce(addOneValue, 0); • Running through the items: 1: 0 => 1 2: 1 => 3 3: 3 => 6 4: 6 => 10 5: 10 => 15
  • 23. Action Reducers in Redux • Take an action and a state, return a new state. • Your app’s state is a reduction over the actions. • Each reducer operates on a subset of the global state. • Simple reducers are combined into complex ones.
  • 24. Creating an Action const UPDATE_NOTE_CONTENT = 'App/UPDATE_NOTE_CONTENT'; function updateNoteContent(noteId, newContent) { return { type: UPDATE_NOTE_CONTENT, payload: { noteId: noteId, newContent: newContent } } }
  • 25. Creating an Action, more ES6 const UPDATE_NOTE_CONTENT = 'App/UPDATE_NOTE_CONTENT'; const updateNoteContent = (noteId, newContent) => ({ type: UPDATE_NOTE_CONTENT, payload: {noteId, newContent} });
  • 26. A Reducer export const notes = createReducer({ [UPDATE_NOTE_CONTENT]: (state, action) => state.setIn( ['byId', action.payload.noteId, 'html'], action.payload.newContent ), [SOME_OTHER_ACTION]: (state, action) => { // do something else or just return state; }), });
  • 27. A Reducer, more ES5ish export const notes = createReducer({ [UPDATE_NOTE_CONTENT]: function (state, action) { return state.setIn( ['byId', action.payload.noteId, 'html'], action.payload.newContent ); }, [SOME_OTHER_ACTION]: function (state, action) { // do something else or just return state; }, });
  • 28. Why Is This a Good Idea? • Reducers are pure functions – easy to understand, easy to test. • Reducers are synchronous. • Data logic is 100% separated from view logic. • You can still have modularity by combining reducers. • New opportunities for tools.
  • 29. How Do We Avoid Mutating State? • Reducers are supposed to not change the old state. But how do we keep them honest? • One option is to clone the object every time. • “Immutable.JS” is the library to use. var newData = data.setIn( ['foo', 'bar', 'baz'], 42 ); • This is a key building block for stateless architecture.
  • 30. The Reducer Example Again export const notes = createReducer({ [UPDATE_NOTE_CONTENT]: (state, action) => state.setIn( ['byId', action.payload.noteId, 'html'], action.payload.newContent ), [SOME_OTHER_ACTION]: (state, action) => { // do something else or just return state; }), });
  • 31. Connecting Container Components import { connect } from 'react-redux'; export default connect( mapStateToProps, mapDispatchToProps, )(MainPage);
  • 32. React-Redux Mapping Functions function mapStateToProps(state) { const notesAsJS = state.notes.toJS(); return { notes: notesAsJS.ordered.map((id) => notesAsJS.byId[id]) }; } function mapDispatchToProps(dispatch) { return { onContentChange: (noteId, newContent) => dispatch(noteActions.updateNoteContent( noteId, newContent)), }; }
  • 33. Handling Asyncronous Actions • Option 1: “Smart” actions creators. • Option 2: Middleware. • Option 2′: React Sagas.
  • 34. Smart Action Creators • Call an action creator to initiate a request. • The action creator emits an action to inform everyone that a request was made. • The action creator makes a request. • If the request succeeds, the action creator emits an action to inform everyone that a request was completed. (Same for failure and timeout.) • The details of interacting with the server should be pushed into a module.
  • 35. An Example, Part 1 function makeFetchNotesAction(status, data) { return { type: FETCH_NOTES, payload: { status: status, data: data } }; }
  • 36. An Example, Part 1 export function fetchNotes() { return dispatch => { dispatch(makeFetchNotesAction('request')); return fetchData() .then(json => dispatch(makeFetchNotesAction('success', json))) .catch(error => dispatch(makeFetchNotesAction('error', error))); }; }
  • 37. Alternatively: Redux Middleware • A middleware is a function that allows you to capture actions and do something before they get to the reducers. • This can include things like API calls. • More generally, the sky is the limit. • Perhaps a little too generic for many cases.
  • 38. Alternative: Redux Sagas • A middleware that works with generators. • Awesome, if you understand generators. • Can simplify complex workflows. • Very new.
  • 39. Redux Sagas Example function* fetchNotesForStack(action) { const stackId = action.payload.stackId; yield put(getNotes.request()); const {data, error} = yield dataApi.getNotesForStack(stackId); if (!error) { yield put(getNotes.success(organizeNotes(data.notes))); } else { yield put(getNotes.failure(error)); } } function* watchFetchNotesForStack() { yield* takeEvery(SELECT_STACK, fetchNotesForStack); }
  • 40. Testing Is Easy describe('on ADD_NOTE', () => { it('should create a new note', () => { const getNoteCount = () => initialState.toJS().ordered.length; const previousCount = getNoteCount(); const newState = notesReducer(initialState, {type: ADD_NOTE}); assert.strictEqual(previousCount + 1, getNoteCount()); const newNoteId = newState.toJS().ordered[0]; const newNoteHtml = newState.getIn(['byId', newNoteId, 'html']); assert.strictEqual(newNoteHtml, 'No content'); }); });
  • 41. Caveats • Its addictive. • You won’t be happy using anything else. • Your friends might not understand your obsession.
  • 42. THANK YOU! Yuri Takhteyev @qaramazov rangle CTO, Rangle.io Some rights reserved - Creative Commons 2.0 by-sa