SlideShare a Scribd company logo
Advanced React
by Mike Wilcox, November 2017
Advanced React
Topics
• YAGNI
• Redux
• React Router
• Presentational and Container Components
• Web Components in React
• Higher Order Components
• Live Code Example
YAGNI
Do You Need Redux?
• Boot from local storage
• Store UI state on server
• Bug reports
• Undo
• Macros / TDD.
• Client side reports or browser extensions
• Swappable UIs
https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367
You might need Redux to:
Redux
The boilerplate to implement Redux is
enormous. If a Redux-specific feature is not
mandated by management, eschew it for
React state, a pub/sub system, or one of
the many Flux alternatives.
I didn’t even mention Redux Forms…
Over-Engineering
Presentational and Container Components
• Containers: Manage data
• Presentationals: Manage DOM
• If you’re using Redux, a Container doesn’t make any sense
• Data fetching should happen in a service, not a component
• A rarely-used pattern in an app
• Better pattern for a library
• More important is determining which component manages
state
• Technically, a Container could manage state too, but then it becomes tightly
coupled
• Example
https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0
React Router
• Now on version 4.x, and the seem to have gotten it right
• Not terribly difficult to use
• Relatively bug-free if used as intended
Curated by React Training, a company that sells training seminars
Pros
Cons
• It took them 4 versions to get it right
• The redux plugin has been in perpetual alpha stage
• The company really pushes their wares
React Router
You don’t have to use React Router
const routes = [
{ path: '/', action: () => <HomePage /> },
{ path: '/tasks', action: () => <TaskList /> },
{ path: '/tasks/:id', action: () => <TaskDetails /> }
];
function renderComponent(component) {
ReactDOM.render(component, container);
}
function render(location) {
router.resolve(routes, location)
.then(renderComponent)
.catch(error => router.resolve(routes, { ...location, error })
.then(renderComponent));
}
For complete code, see reference: https://medium.freecodecamp.org/you-might-not-need-react-router-38673620f3d
Web Components
Web Components
• The React team, while no longer openly hostile, still do not embrace WCs.
• Most events do not work, and you can’t pass in complex data
• Forced to rely upon refs for everything
• Many of the reasons to use JSX are mitigated
• Which means a lot of redundant boiler plate
Web Components
@clubajax/react-web-component
<WebComponent
component="drop-down"
label="Model"
placeholder="Choose Model"
data={this.state.models}
value={this.state.model}
onChange={this.onChooseModel}
/>
The React Web Component makes for a smooth transition between
React and Web Components by allowing to pass objects as
attributes, and listen to custom events.
HOFs/HOCs
HOFs
• Built-in HOFs: map, filter, reduce, etc.
• HOFs do not mutate the variable they are called on
• Ideally, HOFs accept functions with identical signatures
• Composition FTW
Higher-Order Functions
A higher-order function does at least one of the following:
takes one or more functions as arguments (i.e., procedural parameters)
returns a function as its result.
HOFs
const upperCase = (arr) => arr.map(str => str.toUpperCase());
const trim = (arr) => arr.map(str => str.trim());
const dashify = (arr) => arr.map(str => str.replace(/s/g, '-'));
const compose = (...fns) => {
return (...args) => {
return fns.reduce((a, b) => {
return b(a);
}, ...args);
}
};
hof = compose(trim, upperCase, dashify);
hof([' my house ', ' in the middle ', ' of our street ‘]);
// ['MY-HOUSE', 'IN-THE-MIDDLE', 'OF-OUR-STREET']
HOCs
• An advanced technique in React for reusing component logic
• A pattern that emerges from React’s compositional nature
• An HOC is a pure function with zero side-effects
Higher Order Components
A higher-order component is a function that takes a component and returns a new
component.
https://reactjs.org/docs/higher-order-components.html
HOCs
https://reactjs.org/docs/higher-order-components.html
function logProps(WrappedComponent) {
return class extends React.Component {
componentWillReceiveProps(nextProps) {
console.log('Current props: ', this.props);
console.log('Next props: ', nextProps);
}
render() {
// Wraps the input component in a container, without mutating it.
return <WrappedComponent {...this.props} />;
}
}
}
Wrapped Component
class LogComponent extends React.Component {
componentWillReceiveProps (nextProps) {
console.log('Current props: ', this.props);
console.log('Next props: ', nextProps);
}
render () {
return <this.props.component {...this.props} />;
}
}
<LogComponent
component={MyComponent}
title="Foo"
onChange={this.onChange}
/>
A wrapped component is very similar to an HOC. It takes a component as a prop.
HOCs
• Static Methods Must Be Copied Over
• Refs Aren’t Passed Through
• Namespace collisions
• Performance issues
• It is very difficult to make them composable
• Only worthwhile if HOC are truly being reused
• Is the Component a class, a function or an object?
Cons
Render Prop
class Mouse extends React.Component {
handleMouseMove = (e) => {
this.setState({ x: e.clientX, y: e.clientY });
}
render() {
return (
<div onMouseMove={this.handleMouseMove}>
{this.props.render(this.state)}
</div>
const App = React.createClass({
render() {
return (
<div>
<Mouse render={({ x, y }) => (
<h1>The mouse position is ({x}, {y})</h1>
)}/>
</div>
A render prop is a function prop that a component uses to know what to render.
https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce
Live Code Example
https://github.com/clubajax/advanced-react/
Advanced React

More Related Content

What's hot (20)

PDF
Automating Data Flows with the Globus CLI (GlobusWorld Tour - UMich)
Globus
 
PPTX
Nova states summit
Joshua Harlow
 
PDF
Tutorial: Automating Research Data Workflows
Globus
 
PDF
Request-Response Cycle of Ruby on Rails App
Nathalie Steinmetz
 
PDF
(ATS6-PLAT03) What's behind Discngine collections
BIOVIA
 
PPTX
Rails Request & Middlewares
Santosh Wadghule
 
PDF
(ATS6-DEV06) Using Packages for Protocol, Component, and Application Delivery
BIOVIA
 
PPTX
Java web application development
RitikRathaur
 
PPT
Taskflow
Joshua Harlow
 
PPT
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
Nancy Thomas
 
PPTX
ASP.NET MVC 4 Request Pipeline Internals
Lukasz Lysik
 
PPTX
ColdFusion Fw1 (FrameWork1) introduction
SaravanaMuthu Jayaraj
 
PDF
Fw1
poipoiqwe
 
PDF
Jsp & Ajax
Ang Chen
 
PDF
Spring Batch Workshop (advanced)
lyonjug
 
KEY
Spring Batch Behind the Scenes
Joshua Long
 
PPTX
Spring batch showCase
taher abdo
 
PPTX
Spring batch
Chandan Kumar Rana
 
ODP
Http programming in play
Knoldus Inc.
 
PPTX
Writing a massive javascript app
Justin Park
 
Automating Data Flows with the Globus CLI (GlobusWorld Tour - UMich)
Globus
 
Nova states summit
Joshua Harlow
 
Tutorial: Automating Research Data Workflows
Globus
 
Request-Response Cycle of Ruby on Rails App
Nathalie Steinmetz
 
(ATS6-PLAT03) What's behind Discngine collections
BIOVIA
 
Rails Request & Middlewares
Santosh Wadghule
 
(ATS6-DEV06) Using Packages for Protocol, Component, and Application Delivery
BIOVIA
 
Java web application development
RitikRathaur
 
Taskflow
Joshua Harlow
 
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
Nancy Thomas
 
ASP.NET MVC 4 Request Pipeline Internals
Lukasz Lysik
 
ColdFusion Fw1 (FrameWork1) introduction
SaravanaMuthu Jayaraj
 
Jsp & Ajax
Ang Chen
 
Spring Batch Workshop (advanced)
lyonjug
 
Spring Batch Behind the Scenes
Joshua Long
 
Spring batch showCase
taher abdo
 
Spring batch
Chandan Kumar Rana
 
Http programming in play
Knoldus Inc.
 
Writing a massive javascript app
Justin Park
 

Similar to Advanced React (20)

PDF
An Overview of the React Ecosystem
FITC
 
PPTX
How to navigate programmatically using react router
BOSC Tech Labs
 
PDF
Making react part of something greater
Darko Kukovec
 
PPTX
React - Start learning today
Nitin Tyagi
 
PDF
Understanding Facebook's React.js
Federico Torre
 
PDF
Using redux
Jonas Ohlsson Aden
 
PDF
Workshop 27: Isomorphic web apps with ReactJS
Visual Engineering
 
PDF
React loadable
George Bukhanov
 
PPTX
React.js at Cortex
Geoff Harcourt
 
PDF
React js
Rajesh Kolla
 
PPTX
Reactjs notes.pptx for web development- tutorial and theory
jobinThomas54
 
PDF
MidwestJS 2014 Reconciling ReactJS as a View Layer Replacement
Zach Lendon
 
PDF
Reconciling ReactJS as a View Layer Replacement (MidwestJS 2014)
Zach Lendon
 
PDF
A React Journey
LinkMe Srl
 
PPTX
GDSC NITS Presents Kickstart into ReactJS
Pratik Majumdar
 
PPTX
Spfx with react redux
Rajesh Kumar
 
PPTX
How to implement multiple layouts using React router V4.pptx
BOSC Tech Labs
 
PPTX
React JS .NET
Jennifer Estrada
 
PDF
Web Components v1
Mike Wilcox
 
PDF
ReactJS vs AngularJS - Head to Head comparison
500Tech
 
An Overview of the React Ecosystem
FITC
 
How to navigate programmatically using react router
BOSC Tech Labs
 
Making react part of something greater
Darko Kukovec
 
React - Start learning today
Nitin Tyagi
 
Understanding Facebook's React.js
Federico Torre
 
Using redux
Jonas Ohlsson Aden
 
Workshop 27: Isomorphic web apps with ReactJS
Visual Engineering
 
React loadable
George Bukhanov
 
React.js at Cortex
Geoff Harcourt
 
React js
Rajesh Kolla
 
Reactjs notes.pptx for web development- tutorial and theory
jobinThomas54
 
MidwestJS 2014 Reconciling ReactJS as a View Layer Replacement
Zach Lendon
 
Reconciling ReactJS as a View Layer Replacement (MidwestJS 2014)
Zach Lendon
 
A React Journey
LinkMe Srl
 
GDSC NITS Presents Kickstart into ReactJS
Pratik Majumdar
 
Spfx with react redux
Rajesh Kumar
 
How to implement multiple layouts using React router V4.pptx
BOSC Tech Labs
 
React JS .NET
Jennifer Estrada
 
Web Components v1
Mike Wilcox
 
ReactJS vs AngularJS - Head to Head comparison
500Tech
 
Ad

More from Mike Wilcox (20)

PDF
Accessibility for Fun and Profit
Mike Wilcox
 
PDF
WTF R PWAs?
Mike Wilcox
 
PDF
Webpack: What it is, What it does, Whether you need it
Mike Wilcox
 
PDF
Dangerous CSS
Mike Wilcox
 
PDF
Great Responsive-ability Web Design
Mike Wilcox
 
PDF
Professional JavaScript: AntiPatterns
Mike Wilcox
 
PDF
Model View Madness
Mike Wilcox
 
PDF
Hardcore JavaScript – Write it Right
Mike Wilcox
 
KEY
The Great Semicolon Debate
Mike Wilcox
 
KEY
AMD - Why, What and How
Mike Wilcox
 
KEY
Dojo & HTML5
Mike Wilcox
 
KEY
Webpage Design Basics for Non-Designers
Mike Wilcox
 
KEY
Why You Need a Front End Developer
Mike Wilcox
 
KEY
A Conversation About REST
Mike Wilcox
 
KEY
The Fight Over HTML5
Mike Wilcox
 
KEY
The Fight Over HTML5
Mike Wilcox
 
PPT
How to get a Job as a Front End Developer
Mike Wilcox
 
KEY
The History of HTML5
Mike Wilcox
 
KEY
Thats Not Flash?
Mike Wilcox
 
KEY
Flash And Dom
Mike Wilcox
 
Accessibility for Fun and Profit
Mike Wilcox
 
WTF R PWAs?
Mike Wilcox
 
Webpack: What it is, What it does, Whether you need it
Mike Wilcox
 
Dangerous CSS
Mike Wilcox
 
Great Responsive-ability Web Design
Mike Wilcox
 
Professional JavaScript: AntiPatterns
Mike Wilcox
 
Model View Madness
Mike Wilcox
 
Hardcore JavaScript – Write it Right
Mike Wilcox
 
The Great Semicolon Debate
Mike Wilcox
 
AMD - Why, What and How
Mike Wilcox
 
Dojo & HTML5
Mike Wilcox
 
Webpage Design Basics for Non-Designers
Mike Wilcox
 
Why You Need a Front End Developer
Mike Wilcox
 
A Conversation About REST
Mike Wilcox
 
The Fight Over HTML5
Mike Wilcox
 
The Fight Over HTML5
Mike Wilcox
 
How to get a Job as a Front End Developer
Mike Wilcox
 
The History of HTML5
Mike Wilcox
 
Thats Not Flash?
Mike Wilcox
 
Flash And Dom
Mike Wilcox
 
Ad

Recently uploaded (20)

PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
July Patch Tuesday
Ivanti
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
July Patch Tuesday
Ivanti
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 

Advanced React

  • 2. by Mike Wilcox, November 2017 Advanced React
  • 3. Topics • YAGNI • Redux • React Router • Presentational and Container Components • Web Components in React • Higher Order Components • Live Code Example
  • 5. Do You Need Redux? • Boot from local storage • Store UI state on server • Bug reports • Undo • Macros / TDD. • Client side reports or browser extensions • Swappable UIs https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367 You might need Redux to:
  • 6. Redux The boilerplate to implement Redux is enormous. If a Redux-specific feature is not mandated by management, eschew it for React state, a pub/sub system, or one of the many Flux alternatives. I didn’t even mention Redux Forms… Over-Engineering
  • 7. Presentational and Container Components • Containers: Manage data • Presentationals: Manage DOM • If you’re using Redux, a Container doesn’t make any sense • Data fetching should happen in a service, not a component • A rarely-used pattern in an app • Better pattern for a library • More important is determining which component manages state • Technically, a Container could manage state too, but then it becomes tightly coupled • Example https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0
  • 8. React Router • Now on version 4.x, and the seem to have gotten it right • Not terribly difficult to use • Relatively bug-free if used as intended Curated by React Training, a company that sells training seminars Pros Cons • It took them 4 versions to get it right • The redux plugin has been in perpetual alpha stage • The company really pushes their wares
  • 9. React Router You don’t have to use React Router const routes = [ { path: '/', action: () => <HomePage /> }, { path: '/tasks', action: () => <TaskList /> }, { path: '/tasks/:id', action: () => <TaskDetails /> } ]; function renderComponent(component) { ReactDOM.render(component, container); } function render(location) { router.resolve(routes, location) .then(renderComponent) .catch(error => router.resolve(routes, { ...location, error }) .then(renderComponent)); } For complete code, see reference: https://medium.freecodecamp.org/you-might-not-need-react-router-38673620f3d
  • 11. Web Components • The React team, while no longer openly hostile, still do not embrace WCs. • Most events do not work, and you can’t pass in complex data • Forced to rely upon refs for everything • Many of the reasons to use JSX are mitigated • Which means a lot of redundant boiler plate
  • 12. Web Components @clubajax/react-web-component <WebComponent component="drop-down" label="Model" placeholder="Choose Model" data={this.state.models} value={this.state.model} onChange={this.onChooseModel} /> The React Web Component makes for a smooth transition between React and Web Components by allowing to pass objects as attributes, and listen to custom events.
  • 14. HOFs • Built-in HOFs: map, filter, reduce, etc. • HOFs do not mutate the variable they are called on • Ideally, HOFs accept functions with identical signatures • Composition FTW Higher-Order Functions A higher-order function does at least one of the following: takes one or more functions as arguments (i.e., procedural parameters) returns a function as its result.
  • 15. HOFs const upperCase = (arr) => arr.map(str => str.toUpperCase()); const trim = (arr) => arr.map(str => str.trim()); const dashify = (arr) => arr.map(str => str.replace(/s/g, '-')); const compose = (...fns) => { return (...args) => { return fns.reduce((a, b) => { return b(a); }, ...args); } }; hof = compose(trim, upperCase, dashify); hof([' my house ', ' in the middle ', ' of our street ‘]); // ['MY-HOUSE', 'IN-THE-MIDDLE', 'OF-OUR-STREET']
  • 16. HOCs • An advanced technique in React for reusing component logic • A pattern that emerges from React’s compositional nature • An HOC is a pure function with zero side-effects Higher Order Components A higher-order component is a function that takes a component and returns a new component. https://reactjs.org/docs/higher-order-components.html
  • 17. HOCs https://reactjs.org/docs/higher-order-components.html function logProps(WrappedComponent) { return class extends React.Component { componentWillReceiveProps(nextProps) { console.log('Current props: ', this.props); console.log('Next props: ', nextProps); } render() { // Wraps the input component in a container, without mutating it. return <WrappedComponent {...this.props} />; } } }
  • 18. Wrapped Component class LogComponent extends React.Component { componentWillReceiveProps (nextProps) { console.log('Current props: ', this.props); console.log('Next props: ', nextProps); } render () { return <this.props.component {...this.props} />; } } <LogComponent component={MyComponent} title="Foo" onChange={this.onChange} /> A wrapped component is very similar to an HOC. It takes a component as a prop.
  • 19. HOCs • Static Methods Must Be Copied Over • Refs Aren’t Passed Through • Namespace collisions • Performance issues • It is very difficult to make them composable • Only worthwhile if HOC are truly being reused • Is the Component a class, a function or an object? Cons
  • 20. Render Prop class Mouse extends React.Component { handleMouseMove = (e) => { this.setState({ x: e.clientX, y: e.clientY }); } render() { return ( <div onMouseMove={this.handleMouseMove}> {this.props.render(this.state)} </div> const App = React.createClass({ render() { return ( <div> <Mouse render={({ x, y }) => ( <h1>The mouse position is ({x}, {y})</h1> )}/> </div> A render prop is a function prop that a component uses to know what to render. https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce