DEV Community

Cover image for React: Understand higher-order component with a simple example
Yuko
Yuko

Posted on

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

Top comments (0)