SlideShare ist ein Scribd-Unternehmen logo
1 von 94
Downloaden Sie, um offline zu lesen
HigherOrder(Components)
render={props}
> whoami
Nitish Phanse
@nitish24p
Builds stuff @ KyePot
UI = f(Components)
Higher Order Functions
Higher Order Functions
A function which takes one or more
arguments and returns a functions
function multiply() {
}
function multiply(firstNumber) {
return function(secondNumber) {
return firstNumber * secondNumber
}
}
multiply(3)(4)
throttle = (callback: Function, wait: number) => {
};
throttle = (callback: Function, wait: number) => {
let time = Date.now();
return function() {
};
};
throttle = (callback: Function, wait: number) => {
let time = Date.now();
return function() {
if (time + wait - Date.now() < 0) {
callback.apply(this, arguments);
time = Date.now();
}
};
};
throttle = (callback: Function, wait: number) => {
let time = Date.now();
return function() {
if (time + wait - Date.now() < 0) {
callback.apply(this, arguments);
time = Date.now();
}
};
};
<Input onChange={this.throttle(this.handleInputChange, 500)} />
Higher Order Functions
A function which takes one or more
arguments and returns a functions
Higher Order Functions
A function which takes one or more
arguments and returns a functions
Component
Higher Order Functions
A function which takes one or more
arguments and returns a functions
Component
A function which takes a component as an
argument and returns a new component
function myHigherOrderComponent(Component) {
}
function myHigherOrderComponent(Component) {
return class extends React.Component {
}
}
function myHigherOrderComponent(Component) {
return class extends React.Component {
render() {
return <Component />
}
}
}
function myHigherOrderComponent(Component) {
return class extends React.Component {
render() {
return <Component {...this.props}/>
}
}
}
function myHigherOrderComponent(Component) {
return class extends React.Component {
render() {
return <Component {...this.props}/>
}
}
}
export default myHigherOrderComponent(App);

<EnhancedApp foo={bar}/>
Alternative to Mixins Pattern
Encapsulates Logic that can be shared easily
Access data from any part of the component life cycle
Some real world use cases please
Code Splitting
function asyncComponent(importComponent: Function, LoadingComponent: Function) {
class AsyncComponent extends Component {
}
return AsyncComponent;
}
function asyncComponent(importComponent: Function, LoadingComponent: Function) {
class AsyncComponent extends Component {
constructor(props) {
super(props);
this.state = {
component: null
};
}
}
return AsyncComponent;
}
function asyncComponent(importComponent: Function, LoadingComponent: Function) {
class AsyncComponent extends Component {
constructor(props) {
super(props);
this.state = {
component: null
};
}
render() {
const C = this.state.component;
return C ? <C {...this.props} /> : <LoadingComponent />;
}
}
return AsyncComponent;
}
function asyncComponent(importComponent: Function, LoadingComponent: Function) {
class AsyncComponent extends Component {
constructor(props) {
super(props);
this.state = {
component: null
};
}
async componentDidMount() {
const { default: component } = await importComponent();
this.setState({
component: component
});
}
render() {
const C = this.state.component;
return C ? <C {...this.props} /> : <LoadingComponent />;
}
}
return AsyncComponent;
}
class App extends Component {
render() {
<div>
<Switch>
</Switch>
</div>
}
}
const Products = asyncComponent(() => import('./pages/Products'), LoaderComponent);
const HomePage = asyncComponent(() => import('./pages/HomePage'), LoaderComponent);
class App extends Component {
render() {
<div>
<Switch>
<Route exact path={'/'} component={HomePage} />
<Route exact path={'/products'} component={Products} />
</Switch>
</div>
}
}
Server Side Rendering
const wrapComponentWithData = (WrappedComponent) => {
return class CustomComponent extends React.Component {
render() {
return <WrappedComponent {...this.props} />;
}
};
};
const wrapComponentWithData = (WrappedComponent, InitialData) => {
return class CustomComponent extends React.Component {
render() {
return <WrappedComponent {...InitialData} {...this.props} />;
}
};
};
const wrapComponentWithData = (WrappedComponent, InitialData) => {
return class CustomComponent extends React.Component {
render() {
return <WrappedComponent {...InitialData} {...this.props} />;
}
};
};
class App extends Component {
render() {
const data = { this.props }
return (
<div>
<Switch>
<Route exact path={'/'}
component={wrapComponentWithData(Homepage, data)} />
<Route exact path={'/products'}
component={wrapComponentWithData(Products, data)} />
</Switch>
</div>
);
}
}
Data Tracking
import TrackerLib from 'tracker.js'
const withTracking = (Component, pageName, eventObject) => {
};
import TrackerLib from 'tracker.js'
const withTracking = (Component, pageName, eventObject) => {
return class CustomComponent extends React.Component {
render() {
return <Component {...this.props} />;
}
};
};
import TrackerLib from 'tracker.js'
const withTracking = (Component, pageName, eventObject) => {
return class CustomComponent extends React.Component {
componentDidMount() {
TrackerLib.event(pageName, ...eventObject)
}
render() {
return <Component {...this.props} />;
}
};
};
import TrackerLib from 'tracker.js'
const withTracking = (Component, pageName, eventObject) => {
return class CustomComponent extends React.Component {
componentDidMount() {
TrackerLib.event(pageName, ...eventObject)
}
render() {
return <Component {...this.props} />;
}
};
};
export default withTracking(HomePage, 'Home Page', {});
Component Logger
function componentLogger(WrappedComponent) {
return class extends React.Component {
render() {
return <WrappedComponent {...this.props} />;
}
}
}
function componentLogger(WrappedComponent) {
return class extends React.Component {
componentWillReceiveProps(nextProps) {
console.log('Current props: ', this.props);
console.log('Next props: ', nextProps);
}
render() {
return <WrappedComponent {...this.props} />;
}
}
}
function componentLogger(WrappedComponent) {
return class extends React.Component {
componentWillReceiveProps(nextProps) {
console.log('Current props: ', this.props);
console.log('Next props: ', nextProps);
}
render() {
return <WrappedComponent {...this.props} />;
}
}
}
export default componentLogger(HomePage);
Some Handy Tips
Some Handy Tips
Some Handy Tips
Avoid using HOCs inside the render method
Avoid using HOCs inside the render method
Some Handy Tips
render() {
const EnhancedComponent = enhance(MyComponent);
return <EnhancedComponent />;
}
Some Handy Tips
render() {
const EnhancedComponent = enhance(MyComponent);
return <EnhancedComponent />;
}
Avoid using HOCs inside the render method
Refs Aren’t Passed Through
Some Handy Tips
Refs Aren’t Passed Through
Some Handy Tips
function Field({ inputRef, ...rest }) {
return <input ref={inputRef} {...rest} />;
}
Refs Aren’t Passed Through
Some Handy Tips
function Field({ inputRef, ...rest }) {
return <input ref={inputRef} {...rest} />;
}
const EnhancedField = enhance(Field);
<EnhancedField
inputRef={(inputEl) => {
this.inputEl = inputEl
}}
/>
Refs Aren’t Passed Through
Some Handy Tips
function Field({ inputRef, ...rest }) {
return <input ref={inputRef} {...rest} />;
}
const EnhancedField = enhance(Field);
<EnhancedField
inputRef={(inputEl) => {
this.inputEl = inputEl
}}
/>
// Inside Your HOC
this.inputEl.focus();
Common examples of HOC
connect of Redux
createContainer of Relay
Downshift
UrQl
Breathe
Breathe.
Breathe..
Breathe…
Props
A prop is an object for passing data to a
component
Render Prop
A render prop is a function prop that a
component uses to know what to render
class Posts extends React.Component {
state = {
posts: getInitialPostData()
}
render() {
return (
<div>
{this.state.posts.map(post =>
<Post post={post} key={post.id}/>)}
</div>
)
}
}
class Posts extends React.Component {
state = {
posts: getInitialPostData()
}
render() {
return (
<div>
{this.state.posts.map(post =>
<Post post={post} key={post.id}/>)}
</div>
)
}
}
<Posts />
class Posts extends React.Component {
state = {
posts: getInitialPostData()
}
render() {
return (
<div>
{this.state.posts.map(post =>
<Post post={post} key={post.id}/>)}
</div>
)
}
}
class Posts extends React.Component {
state = {
posts: getInitialPostData()
}
render() {
return (
<div>
{this.props.render(this.state)}
</div>
)
}
}
class Posts extends React.Component {
state = {
posts: getInitialPostData()
}
render() {
return (
<div>
{this.props.render(this.state)}
</div>
)
}
}
<Posts
render={({ posts }) =>
posts.map(post => <Post post={post} />)}
/>
Can i use children ???
🤔
class Posts extends React.Component {
state = {
posts: getInitialPostData()
}
render() {
return (
<div>
{this.props.children(this.state)}
</div>
)
}
}
class Posts extends React.Component {
state = {
posts: getInitialPostData()
}
render() {
return (
<div>
{this.props.children(this.state)}
</div>
)
}
}
<Posts>
{
({ posts }) =>
posts.map(post => <Post post={post} />)
}
</Posts>
Fully declarative approach using props
No props naming collision
Eases reusability of components
Where can i use a Render prop?
Async List Fetching
class List extends React.Component {
state = {
list: [],
isLoading: false,
};
componentDidMount() {
this.setState({ isLoading: true }, this.fetchData);
}
fetchData = async () => {
const res = await fetch(this.props.url);
const json = await res.json();
this.setState({
list: json,
isLoading: false,
});
}
}
class List extends React.Component {
state = {
list: [],
isLoading: false,
};
componentDidMount() {
this.setState({ isLoading: true }, this.fetchData);
}
fetchData = async () => {
const res = await fetch(this.props.url);
const json = await res.json();
this.setState({
list: json,
isLoading: false,
});
}
render() {
return this.props.render(this.state);
}
}
<List
url="https://api.github.com/users/nitish24p/repos"
render={
}/>
<List
url="https://api.github.com/users/nitish24p/repos"
render={({ list, isLoading }) => (
<div>
<h2>My repos</h2>
{isLoading && <h2>Loading...</h2>}
<ul>
{list.length > 0 && list.map(repo => (
<li key={repo.id}>
{repo.full_name}
</li>
))}
</ul>
</div>
)} />
Geolocation
class Location extends Component {
}
class Location extends Component {
state = {
latitude: undefined,
longititude: undefined
}
fetchGeoLocation = async () => {
const res = await fetch("api/url");
const json = await res.json();
this.setState({
latitude: json.lat,
longitude: json.long,
});
}
}
class Location extends Component {
state = {
latitude: undefined,
longititude: undefined
}
fetchGeoLocation = async () => {
const res = await fetch("api/url");
const json = await res.json();
this.setState({
latitude: json.lat,
longitude: json.long,
});
}
render() {
const { latitude, longitude } = this.state;
return this.props.children({
latitude,
longitude,
fetchLocation: this.fetchGeoLocation
});
}
}
<Location>
</Location>
<Location>
{({ latitude, longitude, fetchLocation }) => {
}}
</Location>
<Location>
{({ latitude, longitude, fetchLocation }) => {
if (latitude && longitude) {
return <Map marker={latitude, longitude}/>
}
return <Button label='Get Location'
onClick={fetchLocation}/>
}}
</Location>
Handy Tip
Handy Tip
Be careful when using Render Props with
React.PureComponent
Handy Tip
Be careful when using Render Props with
React.PureComponent
Use function reference instead of arrow fn
Handy Tip
this.renderPosts = ({ posts }) => {
return posts.map(post => <Post post={post} />
}
<Posts
render={this.renderPosts}
/>
Common examples of render props
withRouter of React Router
Motion of React Motion
Downshift
UrQl
Can i create a HOC using a Render Prop
Can i create a HOC using a Render Prop
Can i create a HOC using a Render Prop
const withRouter = (Component) => {
const C = (props) => {
const { wrappedComponentRef, ...remainingProps } = props
return (
<Route render={routeComponentProps => (
<Component {...remainingProps}
{...routeComponentProps} ref={wrappedComponentRef} />
)} />
)
}
...
}
function HigherOrderCompCounter(Component) {
return class extends React.Component {
state = {
counter: 0
}
componentDidMount() {
setInterval(() => {
this.setState((prevState) =>
({counter: prevState.counter + 1}));
}, 1000)
}
render () {
return <Component counter={this.state.counter}
{...this.props}/>
}
}
}
const HOCCounter =
HigherOrderCompCounter(CounterComponent);
<HOCCounter />
class Counter extends Component {
state = {
counter: 0
}
componentDidMount() {
setInterval(() => {
this.setState((prevState) =>
({counter: prevState.counter + 1}));
}, 1000)
}
render() {
return this.props.children(this.state);
}
}
<Counter>
{({ counter }) => <h1>{counter}</h1>}
</Counter>
Higher order Component Render Prop
const CounterComponent = ({ counter }) =>
<h1>{counter}</h1>
function HigherOrderCompCounter(Component) {
return class extends React.Component {
state = {
counter: 0
}
componentDidMount() {
setInterval(() => {
this.setState((prevState) =>
({counter: prevState.counter + 1}));
}, 1000)
}
render () {
return <Component counter={this.state.counter}
{...this.props}/>
}
}
}
const HOCCounter =
HigherOrderCompCounter(CounterComponent);
<HOCCounter />
class Counter extends Component {
state = {
counter: 0
}
componentDidMount() {
setInterval(() => {
this.setState((prevState) =>
({counter: prevState.counter + 1}));
}, 1000)
}
render() {
return this.props.children(this.state);
}
}
<Counter>
{({ counter }) => <h1>{counter}</h1>}
</Counter>
Higher order Component Render Prop
const CounterComponent = ({ counter }) =>
<h1>{counter}</h1>
function HigherOrderCompCounter(Component) {
return class extends React.Component {
state = {
counter: 0
}
componentDidMount() {
setInterval(() => {
this.setState((prevState) =>
({counter: prevState.counter + 1}));
}, 1000)
}
render () {
return <Component counter={this.state.counter}
{...this.props}/>
}
}
}
const HOCCounter =
HigherOrderCompCounter(CounterComponent);
<HOCCounter />
class Counter extends Component {
state = {
counter: 0
}
componentDidMount() {
setInterval(() => {
this.setState((prevState) =>
({counter: prevState.counter + 1}));
}, 1000)
}
render() {
return this.props.children(this.state);
}
}
<Counter>
{({ counter }) => <h1>{counter}</h1>}
</Counter>
Higher order Component Render Prop
const CounterComponent = ({ counter }) =>
<h1>{counter}</h1>
function HigherOrderCompCounter(Component) {
return class extends React.Component {
state = {
counter: 0
}
componentDidMount() {
setInterval(() => {
this.setState((prevState) =>
({counter: prevState.counter + 1}));
}, 1000)
}
render () {
return <Component counter={this.state.counter}
{...this.props}/>
}
}
}
const HOCCounter =
HigherOrderCompCounter(CounterComponent);
<HOCCounter />
class Counter extends Component {
state = {
counter: 0
}
componentDidMount() {
setInterval(() => {
this.setState((prevState) =>
({counter: prevState.counter + 1}));
}, 1000)
}
render() {
return this.props.children(this.state);
}
}
<Counter>
{({ counter }) => <h1>{counter}</h1>}
</Counter>
Higher order Component Render Prop
const CounterComponent = ({ counter }) =>
<h1>{counter}</h1>
function HigherOrderCompCounter(Component) {
return class extends React.Component {
state = {
counter: 0
}
componentDidMount() {
setInterval(() => {
this.setState((prevState) =>
({counter: prevState.counter + 1}));
}, 1000)
}
render () {
return <Component counter={this.state.counter}
{...this.props}/>
}
}
}
const HOCCounter =
HigherOrderCompCounter(CounterComponent);
<HOCCounter />
class Counter extends Component {
state = {
counter: 0
}
componentDidMount() {
setInterval(() => {
this.setState((prevState) =>
({counter: prevState.counter + 1}));
}, 1000)
}
render() {
return this.props.children(this.state);
}
}
<Counter>
{({ counter }) => <h1>{counter}</h1>}
</Counter>
Higher order Component Render Prop
const CounterComponent = ({ counter }) =>
<h1>{counter}</h1>
function HigherOrderCompCounter(Component) {
return class extends React.Component {
state = {
counter: 0
}
componentDidMount() {
setInterval(() => {
this.setState((prevState) =>
({counter: prevState.counter + 1}));
}, 1000)
}
render () {
return <Component counter={this.state.counter}
{...this.props}/>
}
}
}
const HOCCounter =
HigherOrderCompCounter(CounterComponent);
<HOCCounter />
class Counter extends Component {
state = {
counter: 0
}
componentDidMount() {
setInterval(() => {
this.setState((prevState) =>
({counter: prevState.counter + 1}));
}, 1000)
}
render() {
return this.props.children(this.state);
}
}
<Counter>
{({ counter }) => <h1>{counter}</h1>}
</Counter>
Higher order Component Render Prop
const CounterComponent = ({ counter }) =>
<h1>{counter}</h1>
Thank you

Weitere ähnliche Inhalte

Was ist angesagt?

React state
React  stateReact  state
React stateDucat
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...Doug Jones
 
Redux Saga - Under the hood
Redux Saga - Under the hoodRedux Saga - Under the hood
Redux Saga - Under the hoodWaqqas Jabbar
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming PrinciplesAndrii Lundiak
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overviewAlex Bachuk
 
How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...Katy Slemon
 
Rethinking Best Practices
Rethinking Best PracticesRethinking Best Practices
Rethinking Best Practicesfloydophone
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga beginsDaniel Franz
 
Redux Sagas - React Alicante
Redux Sagas - React AlicanteRedux Sagas - React Alicante
Redux Sagas - React AlicanteIgnacio Martín
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners Varun Raj
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux IntroductionNikolaus Graf
 

Was ist angesagt? (20)

React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
 
React state
React  stateReact  state
React state
 
Express JS
Express JSExpress JS
Express JS
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
Redux Saga - Under the hood
Redux Saga - Under the hoodRedux Saga - Under the hood
Redux Saga - Under the hood
 
React & Redux
React & ReduxReact & Redux
React & Redux
 
Introduction à React
Introduction à ReactIntroduction à React
Introduction à React
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming Principles
 
React.js and Redux overview
React.js and Redux overviewReact.js and Redux overview
React.js and Redux overview
 
How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...
 
Rethinking Best Practices
Rethinking Best PracticesRethinking Best Practices
Rethinking Best Practices
 
reactJS
reactJSreactJS
reactJS
 
React JS
React JSReact JS
React JS
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga begins
 
Redux Sagas - React Alicante
Redux Sagas - React AlicanteRedux Sagas - React Alicante
Redux Sagas - React Alicante
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
Introduction à React
Introduction à ReactIntroduction à React
Introduction à React
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 

Ähnlich wie Higher Order Components and Render Props

Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react applicationGreg Bergé
 
2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & WebpackCodifly
 
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!JSFestUA
 
Intro to React | DreamLab Academy
Intro to React | DreamLab AcademyIntro to React | DreamLab Academy
Intro to React | DreamLab AcademyDreamLab
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7Dongho Cho
 
Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.Astrails
 
Enhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order componentEnhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order componentYao Nien Chung
 
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
 
Higher-Order Components — Ilya Gelman
Higher-Order Components — Ilya GelmanHigher-Order Components — Ilya Gelman
Higher-Order Components — Ilya Gelman500Tech
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0Eyal Vardi
 
How do we use hooks
How do we use hooksHow do we use hooks
How do we use hooksJim Liu
 
Incremental Type Safety in React Apollo
Incremental Type Safety in React Apollo Incremental Type Safety in React Apollo
Incremental Type Safety in React Apollo Evans Hauser
 
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017Codemotion
 

Ähnlich wie Higher Order Components and Render Props (20)

React lecture
React lectureReact lecture
React lecture
 
React redux
React reduxReact redux
React redux
 
Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react application
 
2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack
 
React hooks
React hooksReact hooks
React hooks
 
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
 
Why react matters
Why react mattersWhy react matters
Why react matters
 
Intro to React | DreamLab Academy
Intro to React | DreamLab AcademyIntro to React | DreamLab Academy
Intro to React | DreamLab Academy
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7
 
Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.
 
Enhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order componentEnhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order component
 
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
 
Higher-Order Components — Ilya Gelman
Higher-Order Components — Ilya GelmanHigher-Order Components — Ilya Gelman
Higher-Order Components — Ilya Gelman
 
Road to react hooks
Road to react hooksRoad to react hooks
Road to react hooks
 
React 101
React 101React 101
React 101
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
How do we use hooks
How do we use hooksHow do we use hooks
How do we use hooks
 
Incremental Type Safety in React Apollo
Incremental Type Safety in React Apollo Incremental Type Safety in React Apollo
Incremental Type Safety in React Apollo
 
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
 

Kürzlich hochgeladen

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Kürzlich hochgeladen (20)

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Higher Order Components and Render Props

  • 5. Higher Order Functions A function which takes one or more arguments and returns a functions
  • 7. function multiply(firstNumber) { return function(secondNumber) { return firstNumber * secondNumber } } multiply(3)(4)
  • 8. throttle = (callback: Function, wait: number) => { };
  • 9. throttle = (callback: Function, wait: number) => { let time = Date.now(); return function() { }; };
  • 10. throttle = (callback: Function, wait: number) => { let time = Date.now(); return function() { if (time + wait - Date.now() < 0) { callback.apply(this, arguments); time = Date.now(); } }; };
  • 11. throttle = (callback: Function, wait: number) => { let time = Date.now(); return function() { if (time + wait - Date.now() < 0) { callback.apply(this, arguments); time = Date.now(); } }; }; <Input onChange={this.throttle(this.handleInputChange, 500)} />
  • 12. Higher Order Functions A function which takes one or more arguments and returns a functions
  • 13. Higher Order Functions A function which takes one or more arguments and returns a functions Component
  • 14. Higher Order Functions A function which takes one or more arguments and returns a functions Component A function which takes a component as an argument and returns a new component
  • 16. function myHigherOrderComponent(Component) { return class extends React.Component { } }
  • 17. function myHigherOrderComponent(Component) { return class extends React.Component { render() { return <Component /> } } }
  • 18. function myHigherOrderComponent(Component) { return class extends React.Component { render() { return <Component {...this.props}/> } } }
  • 19. function myHigherOrderComponent(Component) { return class extends React.Component { render() { return <Component {...this.props}/> } } } export default myHigherOrderComponent(App);
 <EnhancedApp foo={bar}/>
  • 20. Alternative to Mixins Pattern Encapsulates Logic that can be shared easily Access data from any part of the component life cycle
  • 21. Some real world use cases please
  • 23. function asyncComponent(importComponent: Function, LoadingComponent: Function) { class AsyncComponent extends Component { } return AsyncComponent; }
  • 24. function asyncComponent(importComponent: Function, LoadingComponent: Function) { class AsyncComponent extends Component { constructor(props) { super(props); this.state = { component: null }; } } return AsyncComponent; }
  • 25. function asyncComponent(importComponent: Function, LoadingComponent: Function) { class AsyncComponent extends Component { constructor(props) { super(props); this.state = { component: null }; } render() { const C = this.state.component; return C ? <C {...this.props} /> : <LoadingComponent />; } } return AsyncComponent; }
  • 26. function asyncComponent(importComponent: Function, LoadingComponent: Function) { class AsyncComponent extends Component { constructor(props) { super(props); this.state = { component: null }; } async componentDidMount() { const { default: component } = await importComponent(); this.setState({ component: component }); } render() { const C = this.state.component; return C ? <C {...this.props} /> : <LoadingComponent />; } } return AsyncComponent; }
  • 27. class App extends Component { render() { <div> <Switch> </Switch> </div> } }
  • 28. const Products = asyncComponent(() => import('./pages/Products'), LoaderComponent); const HomePage = asyncComponent(() => import('./pages/HomePage'), LoaderComponent); class App extends Component { render() { <div> <Switch> <Route exact path={'/'} component={HomePage} /> <Route exact path={'/products'} component={Products} /> </Switch> </div> } }
  • 30. const wrapComponentWithData = (WrappedComponent) => { return class CustomComponent extends React.Component { render() { return <WrappedComponent {...this.props} />; } }; };
  • 31. const wrapComponentWithData = (WrappedComponent, InitialData) => { return class CustomComponent extends React.Component { render() { return <WrappedComponent {...InitialData} {...this.props} />; } }; };
  • 32. const wrapComponentWithData = (WrappedComponent, InitialData) => { return class CustomComponent extends React.Component { render() { return <WrappedComponent {...InitialData} {...this.props} />; } }; }; class App extends Component { render() { const data = { this.props } return ( <div> <Switch> <Route exact path={'/'} component={wrapComponentWithData(Homepage, data)} /> <Route exact path={'/products'} component={wrapComponentWithData(Products, data)} /> </Switch> </div> ); } }
  • 34. import TrackerLib from 'tracker.js' const withTracking = (Component, pageName, eventObject) => { };
  • 35. import TrackerLib from 'tracker.js' const withTracking = (Component, pageName, eventObject) => { return class CustomComponent extends React.Component { render() { return <Component {...this.props} />; } }; };
  • 36. import TrackerLib from 'tracker.js' const withTracking = (Component, pageName, eventObject) => { return class CustomComponent extends React.Component { componentDidMount() { TrackerLib.event(pageName, ...eventObject) } render() { return <Component {...this.props} />; } }; };
  • 37. import TrackerLib from 'tracker.js' const withTracking = (Component, pageName, eventObject) => { return class CustomComponent extends React.Component { componentDidMount() { TrackerLib.event(pageName, ...eventObject) } render() { return <Component {...this.props} />; } }; }; export default withTracking(HomePage, 'Home Page', {});
  • 39. function componentLogger(WrappedComponent) { return class extends React.Component { render() { return <WrappedComponent {...this.props} />; } } }
  • 40. function componentLogger(WrappedComponent) { return class extends React.Component { componentWillReceiveProps(nextProps) { console.log('Current props: ', this.props); console.log('Next props: ', nextProps); } render() { return <WrappedComponent {...this.props} />; } } }
  • 41. function componentLogger(WrappedComponent) { return class extends React.Component { componentWillReceiveProps(nextProps) { console.log('Current props: ', this.props); console.log('Next props: ', nextProps); } render() { return <WrappedComponent {...this.props} />; } } } export default componentLogger(HomePage);
  • 44. Some Handy Tips Avoid using HOCs inside the render method
  • 45. Avoid using HOCs inside the render method Some Handy Tips render() { const EnhancedComponent = enhance(MyComponent); return <EnhancedComponent />; }
  • 46. Some Handy Tips render() { const EnhancedComponent = enhance(MyComponent); return <EnhancedComponent />; } Avoid using HOCs inside the render method
  • 47. Refs Aren’t Passed Through Some Handy Tips
  • 48. Refs Aren’t Passed Through Some Handy Tips function Field({ inputRef, ...rest }) { return <input ref={inputRef} {...rest} />; }
  • 49. Refs Aren’t Passed Through Some Handy Tips function Field({ inputRef, ...rest }) { return <input ref={inputRef} {...rest} />; } const EnhancedField = enhance(Field); <EnhancedField inputRef={(inputEl) => { this.inputEl = inputEl }} />
  • 50. Refs Aren’t Passed Through Some Handy Tips function Field({ inputRef, ...rest }) { return <input ref={inputRef} {...rest} />; } const EnhancedField = enhance(Field); <EnhancedField inputRef={(inputEl) => { this.inputEl = inputEl }} /> // Inside Your HOC this.inputEl.focus();
  • 51. Common examples of HOC connect of Redux createContainer of Relay Downshift UrQl
  • 56. Props A prop is an object for passing data to a component
  • 57. Render Prop A render prop is a function prop that a component uses to know what to render
  • 58. class Posts extends React.Component { state = { posts: getInitialPostData() } render() { return ( <div> {this.state.posts.map(post => <Post post={post} key={post.id}/>)} </div> ) } }
  • 59. class Posts extends React.Component { state = { posts: getInitialPostData() } render() { return ( <div> {this.state.posts.map(post => <Post post={post} key={post.id}/>)} </div> ) } } <Posts />
  • 60. class Posts extends React.Component { state = { posts: getInitialPostData() } render() { return ( <div> {this.state.posts.map(post => <Post post={post} key={post.id}/>)} </div> ) } }
  • 61. class Posts extends React.Component { state = { posts: getInitialPostData() } render() { return ( <div> {this.props.render(this.state)} </div> ) } }
  • 62. class Posts extends React.Component { state = { posts: getInitialPostData() } render() { return ( <div> {this.props.render(this.state)} </div> ) } } <Posts render={({ posts }) => posts.map(post => <Post post={post} />)} />
  • 63. Can i use children ??? 🤔
  • 64. class Posts extends React.Component { state = { posts: getInitialPostData() } render() { return ( <div> {this.props.children(this.state)} </div> ) } }
  • 65. class Posts extends React.Component { state = { posts: getInitialPostData() } render() { return ( <div> {this.props.children(this.state)} </div> ) } } <Posts> { ({ posts }) => posts.map(post => <Post post={post} />) } </Posts>
  • 66. Fully declarative approach using props No props naming collision Eases reusability of components
  • 67. Where can i use a Render prop?
  • 69. class List extends React.Component { state = { list: [], isLoading: false, }; componentDidMount() { this.setState({ isLoading: true }, this.fetchData); } fetchData = async () => { const res = await fetch(this.props.url); const json = await res.json(); this.setState({ list: json, isLoading: false, }); } }
  • 70. class List extends React.Component { state = { list: [], isLoading: false, }; componentDidMount() { this.setState({ isLoading: true }, this.fetchData); } fetchData = async () => { const res = await fetch(this.props.url); const json = await res.json(); this.setState({ list: json, isLoading: false, }); } render() { return this.props.render(this.state); } }
  • 72. <List url="https://api.github.com/users/nitish24p/repos" render={({ list, isLoading }) => ( <div> <h2>My repos</h2> {isLoading && <h2>Loading...</h2>} <ul> {list.length > 0 && list.map(repo => ( <li key={repo.id}> {repo.full_name} </li> ))} </ul> </div> )} />
  • 74. class Location extends Component { }
  • 75. class Location extends Component { state = { latitude: undefined, longititude: undefined } fetchGeoLocation = async () => { const res = await fetch("api/url"); const json = await res.json(); this.setState({ latitude: json.lat, longitude: json.long, }); } }
  • 76. class Location extends Component { state = { latitude: undefined, longititude: undefined } fetchGeoLocation = async () => { const res = await fetch("api/url"); const json = await res.json(); this.setState({ latitude: json.lat, longitude: json.long, }); } render() { const { latitude, longitude } = this.state; return this.props.children({ latitude, longitude, fetchLocation: this.fetchGeoLocation }); } }
  • 78. <Location> {({ latitude, longitude, fetchLocation }) => { }} </Location>
  • 79. <Location> {({ latitude, longitude, fetchLocation }) => { if (latitude && longitude) { return <Map marker={latitude, longitude}/> } return <Button label='Get Location' onClick={fetchLocation}/> }} </Location>
  • 82. Be careful when using Render Props with React.PureComponent Handy Tip
  • 83. Be careful when using Render Props with React.PureComponent Use function reference instead of arrow fn Handy Tip this.renderPosts = ({ posts }) => { return posts.map(post => <Post post={post} /> } <Posts render={this.renderPosts} />
  • 84. Common examples of render props withRouter of React Router Motion of React Motion Downshift UrQl
  • 85. Can i create a HOC using a Render Prop
  • 86. Can i create a HOC using a Render Prop
  • 87. Can i create a HOC using a Render Prop const withRouter = (Component) => { const C = (props) => { const { wrappedComponentRef, ...remainingProps } = props return ( <Route render={routeComponentProps => ( <Component {...remainingProps} {...routeComponentProps} ref={wrappedComponentRef} /> )} /> ) } ... }
  • 88. function HigherOrderCompCounter(Component) { return class extends React.Component { state = { counter: 0 } componentDidMount() { setInterval(() => { this.setState((prevState) => ({counter: prevState.counter + 1})); }, 1000) } render () { return <Component counter={this.state.counter} {...this.props}/> } } } const HOCCounter = HigherOrderCompCounter(CounterComponent); <HOCCounter /> class Counter extends Component { state = { counter: 0 } componentDidMount() { setInterval(() => { this.setState((prevState) => ({counter: prevState.counter + 1})); }, 1000) } render() { return this.props.children(this.state); } } <Counter> {({ counter }) => <h1>{counter}</h1>} </Counter> Higher order Component Render Prop const CounterComponent = ({ counter }) => <h1>{counter}</h1>
  • 89. function HigherOrderCompCounter(Component) { return class extends React.Component { state = { counter: 0 } componentDidMount() { setInterval(() => { this.setState((prevState) => ({counter: prevState.counter + 1})); }, 1000) } render () { return <Component counter={this.state.counter} {...this.props}/> } } } const HOCCounter = HigherOrderCompCounter(CounterComponent); <HOCCounter /> class Counter extends Component { state = { counter: 0 } componentDidMount() { setInterval(() => { this.setState((prevState) => ({counter: prevState.counter + 1})); }, 1000) } render() { return this.props.children(this.state); } } <Counter> {({ counter }) => <h1>{counter}</h1>} </Counter> Higher order Component Render Prop const CounterComponent = ({ counter }) => <h1>{counter}</h1>
  • 90. function HigherOrderCompCounter(Component) { return class extends React.Component { state = { counter: 0 } componentDidMount() { setInterval(() => { this.setState((prevState) => ({counter: prevState.counter + 1})); }, 1000) } render () { return <Component counter={this.state.counter} {...this.props}/> } } } const HOCCounter = HigherOrderCompCounter(CounterComponent); <HOCCounter /> class Counter extends Component { state = { counter: 0 } componentDidMount() { setInterval(() => { this.setState((prevState) => ({counter: prevState.counter + 1})); }, 1000) } render() { return this.props.children(this.state); } } <Counter> {({ counter }) => <h1>{counter}</h1>} </Counter> Higher order Component Render Prop const CounterComponent = ({ counter }) => <h1>{counter}</h1>
  • 91. function HigherOrderCompCounter(Component) { return class extends React.Component { state = { counter: 0 } componentDidMount() { setInterval(() => { this.setState((prevState) => ({counter: prevState.counter + 1})); }, 1000) } render () { return <Component counter={this.state.counter} {...this.props}/> } } } const HOCCounter = HigherOrderCompCounter(CounterComponent); <HOCCounter /> class Counter extends Component { state = { counter: 0 } componentDidMount() { setInterval(() => { this.setState((prevState) => ({counter: prevState.counter + 1})); }, 1000) } render() { return this.props.children(this.state); } } <Counter> {({ counter }) => <h1>{counter}</h1>} </Counter> Higher order Component Render Prop const CounterComponent = ({ counter }) => <h1>{counter}</h1>
  • 92. function HigherOrderCompCounter(Component) { return class extends React.Component { state = { counter: 0 } componentDidMount() { setInterval(() => { this.setState((prevState) => ({counter: prevState.counter + 1})); }, 1000) } render () { return <Component counter={this.state.counter} {...this.props}/> } } } const HOCCounter = HigherOrderCompCounter(CounterComponent); <HOCCounter /> class Counter extends Component { state = { counter: 0 } componentDidMount() { setInterval(() => { this.setState((prevState) => ({counter: prevState.counter + 1})); }, 1000) } render() { return this.props.children(this.state); } } <Counter> {({ counter }) => <h1>{counter}</h1>} </Counter> Higher order Component Render Prop const CounterComponent = ({ counter }) => <h1>{counter}</h1>
  • 93. function HigherOrderCompCounter(Component) { return class extends React.Component { state = { counter: 0 } componentDidMount() { setInterval(() => { this.setState((prevState) => ({counter: prevState.counter + 1})); }, 1000) } render () { return <Component counter={this.state.counter} {...this.props}/> } } } const HOCCounter = HigherOrderCompCounter(CounterComponent); <HOCCounter /> class Counter extends Component { state = { counter: 0 } componentDidMount() { setInterval(() => { this.setState((prevState) => ({counter: prevState.counter + 1})); }, 1000) } render() { return this.props.children(this.state); } } <Counter> {({ counter }) => <h1>{counter}</h1>} </Counter> Higher order Component Render Prop const CounterComponent = ({ counter }) => <h1>{counter}</h1>