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

PDF
Let's Redux!
PDF
State Models for React with Redux
PPTX
ProvJS: Six Months of ReactJS and Redux
PPTX
Better React state management with Redux
PDF
The Road To Redux
PDF
Let's discover React and Redux with TypeScript
PDF
Redux js
PDF
React & Redux
Let's Redux!
State Models for React with Redux
ProvJS: Six Months of ReactJS and Redux
Better React state management with Redux
The Road To Redux
Let's discover React and Redux with TypeScript
Redux js
React & Redux

What's hot (20)

PDF
Designing applications with Redux
PPTX
React + Redux + TypeScript === ♥
PDF
React for Dummies
PDF
An Introduction to ReactJS
PDF
Introduction to Redux
PPTX
Getting started with Redux js
PDF
React.js and Redux overview
PPTX
React, Flux and a little bit of Redux
PDF
Angular redux
PPT
React js
PDF
React redux
PDF
React state managmenet with Redux
PDF
React + Redux. Best practices
PPTX
Academy PRO: React JS. Redux & Tooling
PPTX
React / Redux Architectures
PDF
Using redux
PPTX
React + Redux Introduction
PPTX
Redux training
PDF
Introduction to React & Redux
PPTX
Introduction to react and redux
Designing applications with Redux
React + Redux + TypeScript === ♥
React for Dummies
An Introduction to ReactJS
Introduction to Redux
Getting started with Redux js
React.js and Redux overview
React, Flux and a little bit of Redux
Angular redux
React js
React redux
React state managmenet with Redux
React + Redux. Best practices
Academy PRO: React JS. Redux & Tooling
React / Redux Architectures
Using redux
React + Redux Introduction
Redux training
Introduction to React & Redux
Introduction to react and redux
Ad

Viewers also liked (20)

PDF
React JS and why it's awesome
PDF
React.js in real world apps.
PDF
How to Redux
PDF
Robust web apps with React.js
PPTX
Flux and redux
PPTX
Reducers+flux=redux
PDF
React&redux
PDF
Redux vs Alt
PPTX
Angular js com diretivas
PPTX
Apresentação AngularJS - Angular UI
PDF
An Intense Overview of the React Ecosystem
PPTX
React, Flux y React native
PDF
React – ¿Qué es React.js?
PDF
JSConf US 2014: Building Isomorphic Apps
PDF
Migrating from Flux to Redux. Why and how.
PPTX
React. Flux. Redux
PDF
Soa Fundamentos
PDF
Arquitetura Orientada a Servicos (SOA)
PDF
Angular js
PPTX
Criando serviços com AngularJS
React JS and why it's awesome
React.js in real world apps.
How to Redux
Robust web apps with React.js
Flux and redux
Reducers+flux=redux
React&redux
Redux vs Alt
Angular js com diretivas
Apresentação AngularJS - Angular UI
An Intense Overview of the React Ecosystem
React, Flux y React native
React – ¿Qué es React.js?
JSConf US 2014: Building Isomorphic Apps
Migrating from Flux to Redux. Why and how.
React. Flux. Redux
Soa Fundamentos
Arquitetura Orientada a Servicos (SOA)
Angular js
Criando serviços com AngularJS
Ad

Similar to Building React Applications with Redux (20)

PDF
Redux essentials
PPTX
Maintaining sanity in a large redux app
PPTX
PDF
Understanding redux
PPTX
React.js at Cortex
PDF
Getting started with React and Redux
PDF
[@NaukriEngineering] Flux Architecture
PDF
Evan Schultz - Angular Summit - 2016
PPTX
Redux workshop
PPTX
React & redux
PPTX
React + Flux = Joy
PPTX
React/Redux
PDF
ReactRedux.pdf
PDF
React Interview Question & Answers PDF By ScholarHat
PPTX
an Introduction to Redux
PDF
A React Journey
PDF
React and redux
PDF
Manage the Flux of your Web Application: Let's Redux
PDF
Content-Driven Apps with React
PPTX
Redux Tech Talk
Redux essentials
Maintaining sanity in a large redux app
Understanding redux
React.js at Cortex
Getting started with React and Redux
[@NaukriEngineering] Flux Architecture
Evan Schultz - Angular Summit - 2016
Redux workshop
React & redux
React + Flux = Joy
React/Redux
ReactRedux.pdf
React Interview Question & Answers PDF By ScholarHat
an Introduction to Redux
A React Journey
React and redux
Manage the Flux of your Web Application: Let's Redux
Content-Driven Apps with React
Redux Tech Talk

More from FITC (20)

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

Recently uploaded (20)

PPTX
nagasai stick diagrams in very large scale integratiom.pptx
PPT
256065457-Anaesthesia-in-Liver-Disease-Patient.ppt
PDF
Dantes Peak Lessons English About Dantes Peak Lessons English About
PPTX
international classification of diseases ICD-10 review PPT.pptx
PPTX
Slides PPTX World Game (s) Eco Economic Epochs.pptx
PDF
RPKI Status Update, presented by Makito Lay at IDNOG 10
PDF
Behind the Smile Unmasking Ken Childs and the Quiet Trail of Deceit Left in H...
PDF
Generative AI Foundations: AI Skills for the Future of Work
PDF
Triggering QUIC, presented by Geoff Huston at IETF 123
PPTX
durere- in cancer tu ttresjjnklj gfrrjnrs mhugyfrd
PDF
Paper PDF World Game (s) Great Redesign.pdf
PDF
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
PPTX
QR Codes Qr codecodecodecodecocodedecodecode
PDF
Project English Paja Jara Alejandro.jpdf
PDF
An introduction to the IFRS (ISSB) Stndards.pdf
PPTX
PPT_M4.3_WORKING WITH SLIDES APPLIED.pptx
PPTX
Job_Card_System_Styled_lorem_ipsum_.pptx
PPTX
Introduction about ICD -10 and ICD11 on 5.8.25.pptx
PDF
The Internet -By the Numbers, Sri Lanka Edition
PPTX
Introduction to Information and Communication Technology
nagasai stick diagrams in very large scale integratiom.pptx
256065457-Anaesthesia-in-Liver-Disease-Patient.ppt
Dantes Peak Lessons English About Dantes Peak Lessons English About
international classification of diseases ICD-10 review PPT.pptx
Slides PPTX World Game (s) Eco Economic Epochs.pptx
RPKI Status Update, presented by Makito Lay at IDNOG 10
Behind the Smile Unmasking Ken Childs and the Quiet Trail of Deceit Left in H...
Generative AI Foundations: AI Skills for the Future of Work
Triggering QUIC, presented by Geoff Huston at IETF 123
durere- in cancer tu ttresjjnklj gfrrjnrs mhugyfrd
Paper PDF World Game (s) Great Redesign.pdf
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
QR Codes Qr codecodecodecodecocodedecodecode
Project English Paja Jara Alejandro.jpdf
An introduction to the IFRS (ISSB) Stndards.pdf
PPT_M4.3_WORKING WITH SLIDES APPLIED.pptx
Job_Card_System_Styled_lorem_ipsum_.pptx
Introduction about ICD -10 and ICD11 on 5.8.25.pptx
The Internet -By the Numbers, Sri Lanka Edition
Introduction to Information and Communication Technology

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