SlideShare uma empresa Scribd logo
1 de 45
Baixar para ler offline
Enhance React app with patterns
part 1: Higher Order Component
Jay Chung (xJkit)

https://github.com/xJkit
https://github.com/xJkit
Sr. Front End Developer
About Me
https://linkedin.com/in/xjkit54780
https://slideshare.net/JOEYCHUNG2
https://twitter.com/xJkit
Jay Chung
Separation of Concern
Higher Order Functions
• Takes one or more functions as arguments
• Returns a function as its result
Higher Order Functions
multThree :: (Num a) => a -> a -> a -> a
multThree x y z = x * y * z
ghci> max 4 5
5
ghci> (max 4) 5
5
Higher Order Functions
Function JavaScript Libraries
MVC
React/Flux
Decoupling
Decoupling by Components
Props
DOM
Component
State
ComponentProps
DOM
Stateful / Class Component
Stateless / Functional Component
Class Component
Props
DOM
Component
State
Props
State
class App extends Component {
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
Props
render() {
const { a, b, c } = functionA(9,4,8,7);
let d;
switch (a) {
case BLUE:
….
d = functionB(5);
break;
case RED:
….
d = functionC(6);
break;
default:
d = “default value”;
break;
}
// ….otherHeavyCompute(9,4,8,7)

Props
render() {
…
…
…
return (
}
<div>
{this.props.isLoading
?
<Loading />
: (
<A>
<B
a={(value) => handleA(value)}
a={(value) => handleB(value)}
a={(value) => handleC(value)}
/>
<C />
</A>
)
}
</div>
State
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
render() {
return <div />
}
State
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
render() {
return <div />
}
State
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
handleFunction() {…}
render() {
return <div />
}
Codes without mindset is a
MESS
I’m missing the declarative HTML…
React Advanced Patterns
Higher Order Component
Render Props
(Part 1)
(Part 2)
Higher Order Component
• Takes one or more components as arguments
• Returns a component as its result
Higher Order Component
const BaseComponent = props => {...}
let EnhancedComponent = pure(BaseComponent)
EnhancedComponent = mapProps(/*...args*/)(EnhancedComponent)
EnhancedComponent = withState(/*...args*/)(EnhancedComponent)
const composedHoc = BaseComponent => hoc1(hoc2(hoc3(BaseComponent)))
or you can compose them:
Higher Order Component
const App = React.createClass({
render() {
// Instead of maintaining our own state,
// we get the mouse position as a prop!
const { x, y } = this.props.mouse
return (
<div style={{ height: '100%' }}>
<h1>The mouse position is ({x}, {y})</h1>
</div>
)
}
})
const withMouse = (Component) => {
return class extends React.Component {
state = { x: 0, y: 0 }
handleMouseMove = (event) => {
this.setState({
x: event.clientX,
y: event.clientY
})
}
render() {
return (
<div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
<Component {...this.props} mouse={this.state}/>
</div>
)
}
}
}
App.js withMouse.js
Enhance you
Higher Order Component
• 	 Code reuse, logic and bootstrap abstraction

• 	 Render Highjacking

• 	 State abstraction and manipulation

• 	 Props manipulation

const AppWithMouse = withMouse(App)
A React utility belt for function components and higher-order components.
Recompose
Think of it like lodash for React.
Recompose
• …lift state into functional wrappers

• ...perform the most common React patterns

• ...optimize rendering performance

• ...interoperate with other libraries
Recompose HoCs
Recompose
• Separate logics to the HoCs (enhancers)

• Make base component to be pure (if no defaultProps)

• Make base component more readable

• Make base component easier to test
HoCs 的使⽤用場景
• Lift States Up

• Common Tasks

• Performance Optimizations

• Observables
Lift States Up
• withProps

• withState

• withHandlers

• withStateHandlers
Common Tasks
• branch

• renderComponent

• renderNothing

• lifecycle
Demo
https://codesandbox.io/embed/1rkopmpl67
https://github.com/xJkit/trendmicro-fed-talk-pattern-hoc.git
Unit Test becomes easier
Functional Components
are easier to test
• Enhancers + Base Component

• Only focus on props change
Recompose makes tests easy
• https://github.com/xJkit/react-goodbye

• A save reminder component for react router v4.
Example: React GoodBye
import { BrowserRouter } from 'react-router-dom';
import { withGoodBye } from 'react-goodbye';
const EnhancedRouter = withGoodBye(BrowserRouter);
ReactDOM.render(
<EnhancedRouter>
<App />
</EnhancedRouter>,
document.getElementById('root')
);
enhancer
• https://github.com/xJkit/react-goodbye

• A save reminder component for react router v4.
describe('withGoodBye', () => {
const BaseComponent = () => <div />;
const EnhancedComponent = withGoodBye(BaseComponent);
test('should receive own props from EnhancedComponent to BaseComponent', () => {
const myProps = { foo: 1, bar: 2 };
const wrapper = shallow(<EnhancedComponent {...myProps}/>);
expect(wrapper.dive().find(BaseComponent).props().foo).toEqual(1);
expect(wrapper.dive().find(BaseComponent).props().bar).toEqual(2);
})
Example: React GoodBye
Ref in HoCs
Ref in HoCs
• If you add a ref to a HOC, the ref will refer to the
outermost container component, not the wrapped
component.

• That’s because ref is not a prop. Like key, it’s handled
differently by React.
Ref in HoCs
• Rename ref prop -> innerRef, otherRef, … whatever

• React v16.3 comes to the rescue: forwardRef
babel-plugin-lodash
import compose from ‘recompose/compose’

import withState from ‘recompose/withState’
import { compose, withState } from ‘recompose’
==== equals to ====
Thank you for your listening

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Easy automation.py
Easy automation.pyEasy automation.py
Easy automation.py
 
Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JS
 
Codeception
CodeceptionCodeception
Codeception
 
Polyglot automation - QA Fest - 2015
Polyglot automation - QA Fest - 2015Polyglot automation - QA Fest - 2015
Polyglot automation - QA Fest - 2015
 
Testing React Applications
Testing React ApplicationsTesting React Applications
Testing React Applications
 
Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...
Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...
Selenide Alternative in Practice - Implementation & Lessons learned [Selenium...
 
Web ui tests examples with selenide, nselene, selene & capybara
Web ui tests examples with  selenide, nselene, selene & capybaraWeb ui tests examples with  selenide, nselene, selene & capybara
Web ui tests examples with selenide, nselene, selene & capybara
 
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
Three Simple Chords of Alternative PageObjects and Hardcore of LoadableCompon...
 
From Good to Great: Functional and Acceptance Testing in WordPress.
From Good to Great: Functional and Acceptance Testing in WordPress.From Good to Great: Functional and Acceptance Testing in WordPress.
From Good to Great: Functional and Acceptance Testing in WordPress.
 
Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]
Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]
Selenide alternative in Python - Introducing Selene [SeleniumCamp 2016]
 
Test automation with php codeception
Test automation with php codeceptionTest automation with php codeception
Test automation with php codeception
 
Automation Abstraction Layers: Page Objects and Beyond
Automation Abstraction Layers: Page Objects and BeyondAutomation Abstraction Layers: Page Objects and Beyond
Automation Abstraction Layers: Page Objects and Beyond
 
Selenium Overview
Selenium OverviewSelenium Overview
Selenium Overview
 
Droidcon ES '16 - How to fail going offline
Droidcon ES '16 - How to fail going offlineDroidcon ES '16 - How to fail going offline
Droidcon ES '16 - How to fail going offline
 
Testing with Codeception
Testing with CodeceptionTesting with Codeception
Testing with Codeception
 
Testing with Codeception (Webelement #30)
Testing with Codeception (Webelement #30)Testing with Codeception (Webelement #30)
Testing with Codeception (Webelement #30)
 
Webdriver cheatsheets summary
Webdriver cheatsheets summaryWebdriver cheatsheets summary
Webdriver cheatsheets summary
 
Front-End Testing: Demystified
Front-End Testing: DemystifiedFront-End Testing: Demystified
Front-End Testing: Demystified
 
Introducing Playwright's New Test Runner
Introducing Playwright's New Test RunnerIntroducing Playwright's New Test Runner
Introducing Playwright's New Test Runner
 
Automated Testing in Angular Slides
Automated Testing in Angular SlidesAutomated Testing in Angular Slides
Automated Testing in Angular Slides
 

Semelhante a Enhance react app with patterns - part 1: higher order component

react-slides.pdf gives information about react library
react-slides.pdf gives information about react libraryreact-slides.pdf gives information about react library
react-slides.pdf gives information about react library
janet736113
 

Semelhante a Enhance react app with patterns - part 1: higher order component (20)

React & The Art of Managing Complexity
React &  The Art of Managing ComplexityReact &  The Art of Managing Complexity
React & The Art of Managing Complexity
 
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
 
React.js: You deserve to know about it
React.js: You deserve to know about itReact.js: You deserve to know about it
React.js: You deserve to know about it
 
react-slides.pptx
react-slides.pptxreact-slides.pptx
react-slides.pptx
 
react-slides.pdf
react-slides.pdfreact-slides.pdf
react-slides.pdf
 
react-slides.pdf gives information about react library
react-slides.pdf gives information about react libraryreact-slides.pdf gives information about react library
react-slides.pdf gives information about react library
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
React lecture
React lectureReact lecture
React lecture
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today
 
OttawaJS - React
OttawaJS - ReactOttawaJS - React
OttawaJS - React
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
 
React js
React jsReact js
React js
 
Lec9Handout.ppt
Lec9Handout.pptLec9Handout.ppt
Lec9Handout.ppt
 
React redux
React reduxReact redux
React redux
 
React for Re-use: Creating UI Components with Confluence Connect
React for Re-use: Creating UI Components with Confluence ConnectReact for Re-use: Creating UI Components with Confluence Connect
React for Re-use: Creating UI Components with Confluence Connect
 
React 16: new features and beyond
React 16: new features and beyondReact 16: new features and beyond
React 16: new features and beyond
 
Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
 
React outbox
React outboxReact outbox
React outbox
 
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
 
A full introductory guide to React
A full introductory guide to ReactA full introductory guide to React
A full introductory guide to React
 

Último

CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Último (20)

W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
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
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
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
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 

Enhance react app with patterns - part 1: higher order component