hoc

what is Custom Higher-Order Components (HOC) ?

  • Profile picture of Mcs
  • by Mcs July 3, 2025

A Higher-Order Component is a function that takes a component and returns a new component with enhanced or additional behavior. Think of it as a wrapper that adds features to a component without modifying the original one.

Basic Syntax:

const withSomething = (WrappedComponent) => {
 return function EnhancedComponent(props) {
   // logic or props manipulation here
   return <WrappedComponent {...props} />;
 };
};

Why Use HOCs?

PurposeExamples
Code reuseAdd logic to multiple components
Cross-cutting logicAuthentication, loading, logging, etc.
AbstractionKeeps components focused on rendering

Example: Intro to Custom HOC

withMessage.js

const withMessage = (WrappedComponent) => {
 return function EnhancedComponent(props) {
   const newMessage = "Message from HOC";

   return <WrappedComponent {...props} message={newMessage} />;
 };
};

export default withMessage;

UserComponent.js

import withMessage from './withMessage';

function User({ message }) {
 return <h2>{message}</h2>;
}

export default withMessage(User);

Now, the User component receives the message via HOC without managing it itself.

Loading HOC (Loader While Data Is Fetching)

Step 1: Create a Loader HOC

const withLoader = (WrappedComponent) => {
 return function WithLoaderComponent({ isLoading, ...props }) {
   if (isLoading) {
     return <p>Loading...</p>;
   }

   return <WrappedComponent {...props} />;
 };
};

export default withLoader;

Step 2: Use the HOC

function App() {
 const [loading, setLoading] = useState(true);
 const [items, setItems] = useState([]);

 useEffect(() => {
   setTimeout(() => {
     setItems(['React', 'Vue', 'Angular']);
     setLoading(false);
   }, 2000);
 }, []);

 return (
   <div>
     <h1>Frontend Frameworks</h1>
     <DataListWithLoader isLoading={loading} data={items} />
   </div>
 );
}

Summary

TermMeaning
HOCFunction that wraps and returns a new enhanced component
Custom HOCAdd reusable logic (e.g., data, auth, props)
withLoaderHOC that conditionally shows a loader
UsagePass props, use conditional rendering

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <br> <p> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <cite> <dl> <dt> <dd> <a hreflang href> <blockquote cite> <ul type> <ol type start> <strong> <em> <code> <li>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.