SlideShare a Scribd company logo
Redux (13) bad practices
Adam Klein
Why this talk?
const reducer = (state, action) => {
...
const item = { ...state.item };
item.some.property = action.payload.newValue;
return {
...state,
item
};
}
Don't mutate the state
import { set } from 'lodash/fp';
const reducer = (state, action) => {
...
return set(
'item.some.property',
action.payload.newValue,
state
);
}
Use immutable libraries
Use redux-freeze in
development
const reducer = (state, action) => {
...
const newState = deepClone(state);
const item = newState.items.find(...);
item.some.property = action.payload.newValue;
return newState;
}
Don't deep clone the state
import { set } from 'lodash/fp';
const reducer = (state, action) => {
...
const index = state.items.findIndex(...);
return set(
['items', index, 'some', 'property'],
action.payload.newValue,
state
);
}
Use immutable libraries
const initialState = {
showSpinner: false
};
Don't name the UI effect
<Button disabled={ this.props.showSpinner } ...>
Send
</Button>
Now it doesn't make sense
const initialState = {
isPending: false
};
Name the data
componentWillReceiveProps(nextProps) {
this.setState({
filteredProducts: nextProps.products.filter(nextProps.filte
})
}
Don't duplicate State
const reducer = (state, action) => {
...
return {
...state,
products: action.payload.products,
filteredProducts:
action.payload.products.filter(state.filter)
};
}
Using Redux !==
Single Source of
Truth
mapStateToProps((state) => ({
filteredProducts: getFilteredProducts(state)
}))
const getFilteredProducts = createSelector(
(state) => state.filter,
(state) => state.products,
(filter, products) => products.filter(filter)
)
Use Selector
render() {
const filteredProducts = this.getFilteredProducts();
return (
...
);
}
If performance is not an issue
function userReducer(state, action) {
switch (action.type) {
case REQUEST_USER:
return { ...state, isLoading: true };
case RECEIVE_USER:
return { ...state, isLoading: false };
...
}
}
function jobReducer(state, action) {
switch (action.type) {
case REQUEST_JOB:
return { ...state, isLoading: true };
case RECEIVE_JOB:
return { ...state, isLoading: false };
...
}
}
Don't duplicate Code
function networkReducer(state, action) {
switch (action.type) {
case START_NETWORK:
return set(
[action.payload.label, 'isLoading'], true, state
)
case END_NETWORK:
return set(
[action.payload.label, 'isLoading'], false, state
)
...
}
}
mapStateToProps((state) => ({
isLoading: state.network.user.isLoading
}))
Dedicated Reducer
const reducer = (state, action) => {
switch (action.type) {
case SET_USER:
localStorage.setItem('userSession', user.session);
return {
user: action.payload
}
}
}
return state;
}
Side Effects from Reducer
Predictable Reducers
Handle side effects in:
middleware
storeEnhancer
componentWillReceiveProps
state subscription
Prefer reacting to state change and not an action
this.props.getData()
.then((data) => {
somethingImperative();
})
Don't use promises
from actions
componentWillReceiveProps(nextProps) {
if (nextProps.data !== this.props.data) {
somethingImperative();
}
}
mapStateToProps = (state) => ({
data: state.data
})
React to state change
posts: {
1: {
id: 1,
title: 'Better Redux',
comments: {
2: {
id: 2,
text: 'Great article!'
}
}
}
}
Don't nest relational
data
posts: {
id: 1,
title: 'Better Redux'
},
comments: {
id: 2,
postId: 1,
text: 'Great article!'
}
Normalized State
Normalized (flat) State
Better describes relational data
Easier to access all objects by ID
Easier to handle and debug
Performance
[
{ id: 1, name: 'Kate' },
{ id: 2, name: 'Jane' }
]
Prefer not to use
arrays
{
1: { id: 1, name: 'Kate' },
2: { id: 2, name: 'Jane' }
}
Key by ID
Tips
lodash keyBy method
Don't omit the ID attribute
{
products: {
1: {
id: 1,
name: 'Shirt',
isSelected: true
},
2: {
id: 2,
name: 'Pants'
}
}
}
Don't mix server data with UI
state
{
products: {
1: {
id: 1,
name: 'Shirt'
},
2: {
id: 2,
name: 'Pants'
}
},
selectedProductIds: {
1: true
}
}
Separate UI State
const mapStateToProps = (state) => {
...state.user
}
Connect too much
const mapStateToProps = (state) => ({
firstName: state.user.firstName,
lastName: state.user.lastName,
});
// or
const mapStateToProps = (state) =>
pick(['firstName', 'lastName'], state.user);
Connect what you need
mapStateToProps = (state) => ({
currentUser: {
id: state.currentUserId,
role: state.currentRole
}
})
New Objects from
mapStateToProps
mapStateToProps = (state) => ({
currentUserId: state.currentUserId,
currentUserRole: state.currentRole
})
Use Primitives
mapStateToProps = (state) => ({
// returns an object:
currentUser: selectCurrentUser(state)
})
Or Selector
const getVisibleTodos = createSelector(
(state, props) => props.filter,
(state, props) => state.todos,
(visibilityFilter, todos) => { ... }
)
const mapStateToProps = (state, props) => {
return {
todos: getVisibleTodos(state, props)
}
}
Don't bust the cache
const makeGetVisibleTodos = () => {
return createSelector(
[ getVisibilityFilter, getTodos ],
(visibilityFilter, todos) => { ... }
)
}
const makeMapStateToProps = () => {
const getVisibleTodos = makeGetVisibleTodos()
const mapStateToProps = (state, props) => {
return {
todos: getVisibleTodos(state, props)
}
}
return mapStateToProps
}
Selector Factory
shameless
promotion time
500Tech.com
angular-up.com
react-next.com
(2018 - coming soon)

More Related Content

What's hot (18)

PDF
Manage the Flux of your Web Application: Let's Redux
Commit University
 
PDF
2018 02-22 React, Redux & Building Applications that Scale | Redux
Codifly
 
PDF
SQL Stored Procedures For My Library Project
Rick Massouh
 
PDF
Quick start with React | DreamLab Academy #2
DreamLab
 
PDF
Recompacting your react application
Greg Bergé
 
PDF
React nocojs
Mark Morris
 
PDF
Ngrx slides
Christoffer Noring
 
PDF
Higher-Order Components — Ilya Gelman
500Tech
 
PDF
React hooks beyond hype
Magdiel Duarte
 
PDF
How should you React to Redux
Brainhub
 
PDF
React lecture
Christoffer Noring
 
PPTX
Ngrx: Redux in angular
Saadnoor Salehin
 
PPTX
Adaptive Data Cleansing with StreamSets and Cassandra
Pat Patterson
 
PDF
Evan Schultz - Angular Summit - 2016
Evan Schultz
 
PPTX
Using Change Streams to Keep Up with Your Data
Evan Rodd
 
KEY
Polyglot parallelism
Phillip Toland
 
Manage the Flux of your Web Application: Let's Redux
Commit University
 
2018 02-22 React, Redux & Building Applications that Scale | Redux
Codifly
 
SQL Stored Procedures For My Library Project
Rick Massouh
 
Quick start with React | DreamLab Academy #2
DreamLab
 
Recompacting your react application
Greg Bergé
 
React nocojs
Mark Morris
 
Ngrx slides
Christoffer Noring
 
Higher-Order Components — Ilya Gelman
500Tech
 
React hooks beyond hype
Magdiel Duarte
 
How should you React to Redux
Brainhub
 
React lecture
Christoffer Noring
 
Ngrx: Redux in angular
Saadnoor Salehin
 
Adaptive Data Cleansing with StreamSets and Cassandra
Pat Patterson
 
Evan Schultz - Angular Summit - 2016
Evan Schultz
 
Using Change Streams to Keep Up with Your Data
Evan Rodd
 
Polyglot parallelism
Phillip Toland
 

Similar to Redux "Bad" Practices - A List of 13 Bad Practices and How to Avoid Them (20)

PDF
Redux essentials
Chandan Kumar Rana
 
PDF
Building React Applications with Redux
FITC
 
PDF
Let's discover React and Redux with TypeScript
Mathieu Savy
 
PPTX
Redux training
dasersoft
 
PDF
Opinionated Approach to Redux
500Tech
 
PDF
React state managmenet with Redux
Vedran Blaženka
 
PPTX
Introduction to react and redux
Cuong Ho
 
PDF
Lean React - Patterns for High Performance [ploneconf2017]
Devon Bernard
 
PPTX
STATE MANAGEMENT IN REACT [Autosaved].pptx
siddheshjadhav919123
 
PDF
How to write bad code in redux (ReactNext 2018)
500Tech
 
PDF
Let's Redux!
Joseph Chiang
 
PDF
Redux js
Nils Petersohn
 
PDF
Redux
Marco Lanaro
 
PPTX
React + Redux Introduction
Nikolaus Graf
 
PPTX
React/Redux
Durgesh Vaishnav
 
PDF
React Interview Question & Answers PDF By ScholarHat
Scholarhat
 
PDF
React+Redux at Scale
C4Media
 
PDF
React + Redux. Best practices
Clickky
 
PDF
Redux Deep Dive - ReactFoo Pune 2018
Aziz Khambati
 
PDF
Advanced Redux architecture - WHAT/WHEN/WHY/HOW
Mateusz Bosek
 
Redux essentials
Chandan Kumar Rana
 
Building React Applications with Redux
FITC
 
Let's discover React and Redux with TypeScript
Mathieu Savy
 
Redux training
dasersoft
 
Opinionated Approach to Redux
500Tech
 
React state managmenet with Redux
Vedran Blaženka
 
Introduction to react and redux
Cuong Ho
 
Lean React - Patterns for High Performance [ploneconf2017]
Devon Bernard
 
STATE MANAGEMENT IN REACT [Autosaved].pptx
siddheshjadhav919123
 
How to write bad code in redux (ReactNext 2018)
500Tech
 
Let's Redux!
Joseph Chiang
 
Redux js
Nils Petersohn
 
React + Redux Introduction
Nikolaus Graf
 
React/Redux
Durgesh Vaishnav
 
React Interview Question & Answers PDF By ScholarHat
Scholarhat
 
React+Redux at Scale
C4Media
 
React + Redux. Best practices
Clickky
 
Redux Deep Dive - ReactFoo Pune 2018
Aziz Khambati
 
Advanced Redux architecture - WHAT/WHEN/WHY/HOW
Mateusz Bosek
 
Ad

More from Adam Klein (10)

PDF
Angular Course - Flux & Redux
Adam Klein
 
PDF
Tales of an open source library
Adam Klein
 
PDF
Es6 everywhere
Adam Klein
 
PDF
Clean up your code
Adam Klein
 
PDF
Ruby for devops
Adam Klein
 
PDF
Lean startups for non-tech entrepreneurs
Adam Klein
 
PDF
Data models in Angular 1 & 2
Adam Klein
 
PDF
Client side unit tests - using jasmine & karma
Adam Klein
 
PDF
Mobile Apps using AngularJS
Adam Klein
 
PDF
3rd party
Adam Klein
 
Angular Course - Flux & Redux
Adam Klein
 
Tales of an open source library
Adam Klein
 
Es6 everywhere
Adam Klein
 
Clean up your code
Adam Klein
 
Ruby for devops
Adam Klein
 
Lean startups for non-tech entrepreneurs
Adam Klein
 
Data models in Angular 1 & 2
Adam Klein
 
Client side unit tests - using jasmine & karma
Adam Klein
 
Mobile Apps using AngularJS
Adam Klein
 
3rd party
Adam Klein
 
Ad

Recently uploaded (20)

PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
PPTX
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
PPT
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
July Patch Tuesday
Ivanti
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Python basic programing language for automation
DanialHabibi2
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
July Patch Tuesday
Ivanti
 

Redux "Bad" Practices - A List of 13 Bad Practices and How to Avoid Them