Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of React HOC for Functional Components

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?
like image 311
copenndthagen Avatar asked Dec 01 '25 09:12

copenndthagen


1 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 :

  • Render Props: React Docs on Render Props
  • Using Custom Hooks over HOC Article on custom hooks

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.

like image 84
Priyankar Kumar Avatar answered Dec 03 '25 22:12

Priyankar Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!