SlideShare una empresa de Scribd logo
1 de 26
Descargar para leer sin conexión
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.

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado

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
 

Destacado (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
 

Similar a 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
 

Similar a 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
 

Más de 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
 

Más de 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
 

Último

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 

Último (20)

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 

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.