Usage of React HOC for Functional Components

Viewed 5320

I was referring to the below link (section : HOCs for Functional Components) https://rossbulat.medium.com/how-to-use-react-higher-order-components-c0be6821eb6c

In the example, below is the code for the HOC;

//functional HOC with useState hook
import React, { useState } from 'react';
function withCountState(Wrapped) {
   return function (props) {
      const [count, setCount] = useState(0);
  
      props['count'] = count;
      props['setCount'] = setCount;
      return <Wrapped {...props} />;
   }
}

Also, the Wrapped component code is as below;

const Wrapped = (props) =>  {
   const {count, setCount} = props;
   return(
     <div>
        <h1>Counter Functional Component</h1>
        <p>You clicked {count} times</p>
        <button onClick={() => setCount(count + 1)}>
           Increment count
        </button>
     </div>);
};

For applying HOC to , we use

const EnhancedWrapped = withCountState(Wrapped);

Now I have 2 questions;

  1. For consuming this component, do we just say <EnhancedWrapped> may be in our App.js or do we need anything else?
  2. What benefit do we really get out of creating this HOC?
2 Answers

Viet has answered your questions. HOC is a way to make your components re-usable through composition. You can have other components which get wrapped by the HOC and now they would have access to the count and setCount functionality.

Depending upon what you are trying to accomplish, it's also a good idea to consider the pitfalls of HOC and consider alternate patterns such as :

When using React Hooks, I'd personally prefer making custom hooks over using HOCs. And depending upon the use case, you may want to check out if React Context would make sense if multiple components are going to need a shared state.

  1. For consuming this component, do we just say may be in our App.js or do we need anything else? Yes, just use HOC like any other JSX component.

  2. What benefit do we really get out of creating this HOC? You can make it reusable. Let's say you want another component with different content inside, like , you could just create a new component by const AnotherEnhancedWrapped = withCountState(AnotherWrapped);

Related