Yuko
Posted on March 8, 2022
This is my memo about React higher-order components with an example.
According to the official document,
a higher-order component is a function that takes a component and returns a new component.
const EnhancedComponent = higherOrderComponent(WrappedComponent);
HOC is useful when you want to reuse components logic.
This is the image of the example app.
This is the structure of files in src folder.
IncrementWrapper.jsx
import { useState } from "react"
const IncrementWrapper = (WrappedComponent, incrementValue)=>{
const HOC = () => {
const [value, setValue] = useState(0);
const incrementHandler = () => {
setValue(value + incrementValue)
}
return <WrappedComponent value={value} incrementHandler={incrementHandler} />
}
return HOC
}
export default IncrementWrapper;
IncrementBy1.jsx
import IncrementWrapper from "../hoc/IncrementWrapper"
const IncrementBy1 = ({value, incrementHandler}) => <>
<button onClick={incrementHandler}>Increment By 1</button>
<h1>{value}</h1>
</>
export default IncrementWrapper(IncrementBy1, 1)
IncrementBy10.jsx
import IncrementWrapper from "../hoc/IncrementWrapper"
const IncrementBy10 = ({value, incrementHandler}) => <>
<button onClick={incrementHandler}>Increment By 10</button>
<h1>{value}</h1>
</>
export default IncrementWrapper(IncrementBy10, 10)
IncrementBy100.jsx
import IncrementWrapper from "../hoc/IncrementWrapper"
const IncrementBy100 = ({value, incrementHandler}) => <>
<button onClick={incrementHandler}>Increment By 100</button>
<h1>{value}</h1>
</>
export default IncrementWrapper(IncrementBy100, 100)
The whole code is available here.
Thank you for reading :)
The original article is here
đź’– đź’Ş đź™… đźš©
Yuko
Posted on March 8, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.