SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Downloaden Sie, um offline zu lesen
Purifying
@robinpokorny
React
Hi, I will share how we made our front end pure, by
incrementally introducing Redux, ImmutableJS, and higher-order
components, all under constant requests for new features.
I’m Robin and I met React on the internet.
We've been together since.
Nine months ago I joined Wimdu to help it with its front end.
Our site is server-rendered by Rails.
We have a growing number of async-loaded independent
React components to enhance the page.
The problem occurred when we wanted them to
communicate amongst themselves.
We decided to implement a state container— Redux.
We only introduced Redux when we felt we needed it.
We try to avoid premature optimisation and over-engineering.
As we were aware that a rewrite would be too big, paralysing
us for weeks we came up with an incremental process.
Now, we need to purify our code base…
‘Pure’ is a concept in functional programming (learn more).
We start purifying at the bottom—individual functions.
This was not a project or task. We only refactored code we
were touching during our regular work.
Functionthis to params
First step was easy.
Get rid of this and pass data in parameters.
Only lifecycle function could still access this.
renderGroups() {
const { groups } = this.props
…
}
renderGroups(groups) {
…
}
instacod.es/107138
Old
New
Second step proved to be more challenging.
Instead of changing the object, function should return
changed object without modifying the original.
const addParam = (options, name, param) => {
options[name] = param
}
const addParam = (options, name, param) => {
return Object.assign(
{},
options,
{ [name]: param }
)
}
instacod.es/107139
When all functions in a component are pure,

we make the component pure, too
Function
Component
this to params
state to props
This means a component should only depend on its props.
Everything in state was moved to the parent component’s
state and passes down via props.
propstate
This is how an ideal pure component looks like.
Note that we are thoroughly describing propTypes.
They serve also as a documentation.
const MyComponent = ({ steps, modifier = '' }) => (
<div class={ modifier }>
…
)
MyComponent.propTypes = {
steps: PropTypes.arrayOf(
PropTypes.shape({
completed: PropTypes.bool.isRequired,
title: PropTypes.string.isRequired
})
).isRequired,
modifier: PropTypes.string
}
instacod.es/107140
Now when all children components are pure

we can make the top-level container pure too.
Only this container is aware of the data flow.
Function
Component
Container
this to params
state to props
all in state
All data is inside this container’s state.
Modifications are possible only with provided methods.
MyComponent passes these ‘actions’ further.
import MyComponent from './my-component'
class Wrapper extends React.Component {
constructor() {
this.state = {
active: false,
list: [],
};
}
open() { … }
close() { … }
render() {
return (<MyComponent
{...this.state}
onOpen={this.openScratchpad.bind(this)}
onClose={this.closeScratchpad.bind(this)}
translations={this.props.translations}
/>)
}
}
export default Wrapper
instacod.es/107146
Introducing Redux is now easy.
We have the data structure described.
All components keep their APIs (= propTypes).
Function
Component
Container
Redux
this to params
state to props
state to store
all in state
We can remove the Wrapper and connect to Redux.
Data is now in store, actions correspond to methods.
MyComponent has not changed.
instacod.es/107141
As mentioned earlier, our app is in fact Rails app.
The react-rails gem enables mounting React in templates.
It also passes data from Rails to the component.
react-rails
To pass the initial state (from multiple templates) we
serialise it to JSON and append it to the array.
Component is referenced by (global) variable name.
instacod.es/107136
Thanks to ImmutableJS deep merging method we
combine all partial states into one store.
We use tx to pass this store to the component.
import tx from 'transform-props-with'
if (!window.Wimdu.store) {
const initialState =
Map().mergeDeep(...window.__INITIAL_STATE__)
window.Wimdu.store = configureStore({ initialState })
}
window.Wimdu.MyComponent =
tx({ store: window.Wimdu.store })(MyComponent)
instacod.es/107137
Changing data handling in Redux we introduce

immutable structures (e.g. ImmutableJS).
No need to touch anything else.
Function
Component
Container
Redux
this to params
state to props
state to store
immutable
all in state
This is an example Redux reducer.
Thanks to Records we have structure consistency,
documentation, and dot access notation.
instacod.es/107142
Unfortunately it is difficult to have Record of Records.
For namespacing we combine reduces the usual way.
Leafs (and only leafs) of reducer tree are Records.
instacod.es/107143
instacod.es/107144
To ensure backwards compatibility we convert immutable
structures to simple JS objects at first.
We ‘immutablyfy’ a component passing JS to its children.
First we went UP—purifying from smallest parts.
We introduced immutability at the top and went back DOWN.
Function
Component
Container
Redux
this to params
state to props
state to store
immutable
all in state
Download this slide as a one-page summary: http://buff.ly/1XbtFpH
I am fond of Elm (although not on the production now).
It helps me to decide how to structure the app.
Both React and Redux are inspired by Elm.
‘How would I do it in Elm?’
A secret tip for better React and Redux apps:
I want to thank my team for their hard work. You made this happen!
Any question or feedback is welcomed.
@robinpokorny me@robinpokorny.com
Cover image was taken from 1952 Kaiser Aluminum ad:

http://www.fulltable.com/vts/f/fut/f/world/SH536.jpg
Image on the last slide is taken from a postcard:
Fission Room, Niagara Mohawk Progress Center, Nine Mile Point, NY
This work by Robin Pokorny is licensed under a
Creative Commons Attribution 4.0 International License.

Weitere ähnliche Inhalte

Was ist angesagt?

React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to HooksSoluto
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 
Internationalizing react apps
Internationalizing react appsInternationalizing react apps
Internationalizing react appsGeorge Bukhanov
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming PrinciplesAndrii Lundiak
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 DreamLab
 
Deep Dive into React Hooks
Deep Dive into React HooksDeep Dive into React Hooks
Deep Dive into React HooksFelix Kühl
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.jsEmanuele DelBono
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015   by Max PetruckReact, Redux, ES2015   by Max Petruck
React, Redux, ES2015 by Max PetruckMaksym Petruk
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2DreamLab
 
Introduction to Everit Component Registry - B Zsoldos
Introduction to Everit Component Registry - B ZsoldosIntroduction to Everit Component Registry - B Zsoldos
Introduction to Everit Component Registry - B Zsoldosmfrancis
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsMihail Gaberov
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with ReduxFITC
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsANKUSH CHAVAN
 
Synchronizing concurrent threads
Synchronizing concurrent threadsSynchronizing concurrent threads
Synchronizing concurrent threadslactrious
 
React hooks beyond hype
React hooks beyond hypeReact hooks beyond hype
React hooks beyond hypeMagdiel Duarte
 

Was ist angesagt? (19)

React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Internationalizing react apps
Internationalizing react appsInternationalizing react apps
Internationalizing react apps
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming Principles
 
React hooks
React hooksReact hooks
React hooks
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
 
Deep Dive into React Hooks
Deep Dive into React HooksDeep Dive into React Hooks
Deep Dive into React Hooks
 
"this" in JavaScript
"this" in JavaScript"this" in JavaScript
"this" in JavaScript
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015   by Max PetruckReact, Redux, ES2015   by Max Petruck
React, Redux, ES2015 by Max Petruck
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2
 
React with Redux
React with ReduxReact with Redux
React with Redux
 
Introduction to Everit Component Registry - B Zsoldos
Introduction to Everit Component Registry - B ZsoldosIntroduction to Everit Component Registry - B Zsoldos
Introduction to Everit Component Registry - B Zsoldos
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIs
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
 
ReactJS (1)
ReactJS (1)ReactJS (1)
ReactJS (1)
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle Methods
 
Synchronizing concurrent threads
Synchronizing concurrent threadsSynchronizing concurrent threads
Synchronizing concurrent threads
 
React hooks beyond hype
React hooks beyond hypeReact hooks beyond hype
React hooks beyond hype
 

Andere mochten auch

React a omyly jazyka CSS
React a omyly jazyka CSSReact a omyly jazyka CSS
React a omyly jazyka CSSRobin Pokorny
 
React, když odezní zamilovanost
React, když odezní zamilovanostReact, když odezní zamilovanost
React, když odezní zamilovanostRobin Pokorny
 
React z pohledu UI vývojáře
React z pohledu UI vývojářeReact z pohledu UI vývojáře
React z pohledu UI vývojářeMartin Pešout
 
New methods for exploiting ORM injections in Java applications
New methods for exploiting ORM injections in Java applicationsNew methods for exploiting ORM injections in Java applications
New methods for exploiting ORM injections in Java applicationsMikhail Egorov
 

Andere mochten auch (6)

React a omyly jazyka CSS
React a omyly jazyka CSSReact a omyly jazyka CSS
React a omyly jazyka CSS
 
React a CSS
React a CSSReact a CSS
React a CSS
 
React, když odezní zamilovanost
React, když odezní zamilovanostReact, když odezní zamilovanost
React, když odezní zamilovanost
 
React z pohledu UI vývojáře
React z pohledu UI vývojářeReact z pohledu UI vývojáře
React z pohledu UI vývojáře
 
Why not ORM
Why not ORMWhy not ORM
Why not ORM
 
New methods for exploiting ORM injections in Java applications
New methods for exploiting ORM injections in Java applicationsNew methods for exploiting ORM injections in Java applications
New methods for exploiting ORM injections in Java applications
 

Ähnlich wie Purifying React (with annotations)

React js programming concept
React js programming conceptReact js programming concept
React js programming conceptTariqul islam
 
Into React-DOM.pptx
Into React-DOM.pptxInto React-DOM.pptx
Into React-DOM.pptxRan Wahle
 
React for Dummies
React for DummiesReact for Dummies
React for DummiesMitch Chen
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react jsStephieJohn
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥Remo Jansen
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with ReduxVedran Blaženka
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfStephieJohn
 
Workshop 22: React-Redux Middleware
Workshop 22: React-Redux MiddlewareWorkshop 22: React-Redux Middleware
Workshop 22: React-Redux MiddlewareVisual Engineering
 
Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedVisual Engineering
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
Content-Driven Apps with React
Content-Driven Apps with ReactContent-Driven Apps with React
Content-Driven Apps with ReactNetcetera
 
N Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React NativeN Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React NativeAnton Kulyk
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тягаVitebsk Miniq
 
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...Edureka!
 
How to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksHow to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksKaty Slemon
 

Ähnlich wie Purifying React (with annotations) (20)

Simple React Todo List
Simple React Todo ListSimple React Todo List
Simple React Todo List
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
Into React-DOM.pptx
Into React-DOM.pptxInto React-DOM.pptx
Into React-DOM.pptx
 
React for Dummies
React for DummiesReact for Dummies
React for Dummies
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
React/Redux
React/ReduxReact/Redux
React/Redux
 
Lec7Handout.ppt
Lec7Handout.pptLec7Handout.ppt
Lec7Handout.ppt
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
 
Intro react js
Intro react jsIntro react js
Intro react js
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdf
 
Workshop 22: React-Redux Middleware
Workshop 22: React-Redux MiddlewareWorkshop 22: React-Redux Middleware
Workshop 22: React-Redux Middleware
 
Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux Advanced
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Content-Driven Apps with React
Content-Driven Apps with ReactContent-Driven Apps with React
Content-Driven Apps with React
 
N Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React NativeN Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React Native
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тяга
 
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
 
How to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksHow to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooks
 

Mehr von Robin Pokorny

Co musí umět moderní „HTML kodér“
Co musí umět moderní „HTML kodér“Co musí umět moderní „HTML kodér“
Co musí umět moderní „HTML kodér“Robin Pokorny
 
Pokročilé responzivní obrázky
Pokročilé responzivní obrázkyPokročilé responzivní obrázky
Pokročilé responzivní obrázkyRobin Pokorny
 
O elementu picture v Ostravě
O elementu picture v OstravěO elementu picture v Ostravě
O elementu picture v OstravěRobin Pokorny
 
Jak nám responzivní web rozbil obrázky
Jak nám responzivní web rozbil obrázkyJak nám responzivní web rozbil obrázky
Jak nám responzivní web rozbil obrázkyRobin Pokorny
 
Organizace kódu v týmu
Organizace kódu v týmuOrganizace kódu v týmu
Organizace kódu v týmuRobin Pokorny
 
How to Turn Your Ugly Old CSS into a Clean Future-Ready Beauty
How to Turn Your Ugly Old CSS into a Clean Future-Ready BeautyHow to Turn Your Ugly Old CSS into a Clean Future-Ready Beauty
How to Turn Your Ugly Old CSS into a Clean Future-Ready BeautyRobin Pokorny
 
Thesis defendence presentation
Thesis defendence presentationThesis defendence presentation
Thesis defendence presentationRobin Pokorny
 
Tancuj, tancuj, konverguj
Tancuj, tancuj, konvergujTancuj, tancuj, konverguj
Tancuj, tancuj, konvergujRobin Pokorny
 

Mehr von Robin Pokorny (10)

15 months of AMP
15 months of AMP15 months of AMP
15 months of AMP
 
Co musí umět moderní „HTML kodér“
Co musí umět moderní „HTML kodér“Co musí umět moderní „HTML kodér“
Co musí umět moderní „HTML kodér“
 
Pokročilé responzivní obrázky
Pokročilé responzivní obrázkyPokročilé responzivní obrázky
Pokročilé responzivní obrázky
 
O elementu picture v Ostravě
O elementu picture v OstravěO elementu picture v Ostravě
O elementu picture v Ostravě
 
Jak nám responzivní web rozbil obrázky
Jak nám responzivní web rozbil obrázkyJak nám responzivní web rozbil obrázky
Jak nám responzivní web rozbil obrázky
 
Organizace kódu v týmu
Organizace kódu v týmuOrganizace kódu v týmu
Organizace kódu v týmu
 
How to Turn Your Ugly Old CSS into a Clean Future-Ready Beauty
How to Turn Your Ugly Old CSS into a Clean Future-Ready BeautyHow to Turn Your Ugly Old CSS into a Clean Future-Ready Beauty
How to Turn Your Ugly Old CSS into a Clean Future-Ready Beauty
 
Thesis defendence presentation
Thesis defendence presentationThesis defendence presentation
Thesis defendence presentation
 
Tancuj, tancuj, konverguj
Tancuj, tancuj, konvergujTancuj, tancuj, konverguj
Tancuj, tancuj, konverguj
 
Představení eMAMS
Představení eMAMSPředstavení eMAMS
Představení eMAMS
 

Kürzlich hochgeladen

Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 

Kürzlich hochgeladen (20)

Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 

Purifying React (with annotations)

  • 1. Purifying @robinpokorny React Hi, I will share how we made our front end pure, by incrementally introducing Redux, ImmutableJS, and higher-order components, all under constant requests for new features.
  • 2. I’m Robin and I met React on the internet. We've been together since. Nine months ago I joined Wimdu to help it with its front end.
  • 3. Our site is server-rendered by Rails. We have a growing number of async-loaded independent React components to enhance the page.
  • 4. The problem occurred when we wanted them to communicate amongst themselves. We decided to implement a state container— Redux.
  • 5. We only introduced Redux when we felt we needed it. We try to avoid premature optimisation and over-engineering. As we were aware that a rewrite would be too big, paralysing us for weeks we came up with an incremental process. Now, we need to purify our code base… ‘Pure’ is a concept in functional programming (learn more).
  • 6. We start purifying at the bottom—individual functions. This was not a project or task. We only refactored code we were touching during our regular work. Functionthis to params
  • 7. First step was easy. Get rid of this and pass data in parameters. Only lifecycle function could still access this. renderGroups() { const { groups } = this.props … } renderGroups(groups) { … } instacod.es/107138 Old New
  • 8. Second step proved to be more challenging. Instead of changing the object, function should return changed object without modifying the original. const addParam = (options, name, param) => { options[name] = param } const addParam = (options, name, param) => { return Object.assign( {}, options, { [name]: param } ) } instacod.es/107139
  • 9. When all functions in a component are pure,
 we make the component pure, too Function Component this to params state to props
  • 10. This means a component should only depend on its props. Everything in state was moved to the parent component’s state and passes down via props. propstate
  • 11. This is how an ideal pure component looks like. Note that we are thoroughly describing propTypes. They serve also as a documentation. const MyComponent = ({ steps, modifier = '' }) => ( <div class={ modifier }> … ) MyComponent.propTypes = { steps: PropTypes.arrayOf( PropTypes.shape({ completed: PropTypes.bool.isRequired, title: PropTypes.string.isRequired }) ).isRequired, modifier: PropTypes.string } instacod.es/107140
  • 12. Now when all children components are pure
 we can make the top-level container pure too. Only this container is aware of the data flow. Function Component Container this to params state to props all in state
  • 13. All data is inside this container’s state. Modifications are possible only with provided methods. MyComponent passes these ‘actions’ further. import MyComponent from './my-component' class Wrapper extends React.Component { constructor() { this.state = { active: false, list: [], }; } open() { … } close() { … } render() { return (<MyComponent {...this.state} onOpen={this.openScratchpad.bind(this)} onClose={this.closeScratchpad.bind(this)} translations={this.props.translations} />) } } export default Wrapper instacod.es/107146
  • 14. Introducing Redux is now easy. We have the data structure described. All components keep their APIs (= propTypes). Function Component Container Redux this to params state to props state to store all in state
  • 15. We can remove the Wrapper and connect to Redux. Data is now in store, actions correspond to methods. MyComponent has not changed. instacod.es/107141
  • 16. As mentioned earlier, our app is in fact Rails app. The react-rails gem enables mounting React in templates. It also passes data from Rails to the component. react-rails
  • 17. To pass the initial state (from multiple templates) we serialise it to JSON and append it to the array. Component is referenced by (global) variable name. instacod.es/107136
  • 18. Thanks to ImmutableJS deep merging method we combine all partial states into one store. We use tx to pass this store to the component. import tx from 'transform-props-with' if (!window.Wimdu.store) { const initialState = Map().mergeDeep(...window.__INITIAL_STATE__) window.Wimdu.store = configureStore({ initialState }) } window.Wimdu.MyComponent = tx({ store: window.Wimdu.store })(MyComponent) instacod.es/107137
  • 19. Changing data handling in Redux we introduce
 immutable structures (e.g. ImmutableJS). No need to touch anything else. Function Component Container Redux this to params state to props state to store immutable all in state
  • 20. This is an example Redux reducer. Thanks to Records we have structure consistency, documentation, and dot access notation. instacod.es/107142
  • 21. Unfortunately it is difficult to have Record of Records. For namespacing we combine reduces the usual way. Leafs (and only leafs) of reducer tree are Records. instacod.es/107143
  • 22. instacod.es/107144 To ensure backwards compatibility we convert immutable structures to simple JS objects at first. We ‘immutablyfy’ a component passing JS to its children.
  • 23. First we went UP—purifying from smallest parts. We introduced immutability at the top and went back DOWN. Function Component Container Redux this to params state to props state to store immutable all in state Download this slide as a one-page summary: http://buff.ly/1XbtFpH
  • 24. I am fond of Elm (although not on the production now). It helps me to decide how to structure the app. Both React and Redux are inspired by Elm. ‘How would I do it in Elm?’ A secret tip for better React and Redux apps:
  • 25. I want to thank my team for their hard work. You made this happen! Any question or feedback is welcomed. @robinpokorny me@robinpokorny.com
  • 26. Cover image was taken from 1952 Kaiser Aluminum ad:
 http://www.fulltable.com/vts/f/fut/f/world/SH536.jpg Image on the last slide is taken from a postcard: Fission Room, Niagara Mohawk Progress Center, Nine Mile Point, NY This work by Robin Pokorny is licensed under a Creative Commons Attribution 4.0 International License.