React: Understand higher-order component with a simple example

lada496

Yuko

Posted on March 8, 2022

React: Understand higher-order component with a simple example

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);
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

The whole code is available here.

Thank you for reading :)

The original article is here

đź’– đź’Ş đź™… đźš©
lada496
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.

Related