What are Higher Order Components in ReactJS?

💭Imagine This:

Think of a Higher-Order Component (HOC) like a wrapper around another component, just like a tree that grows another tree inside it and then gives back that tree!
So Higher-Order Component is a function that takes a component, adds some extra features, and then returns an enhanced component.

🤔But Why Use HOCs?

  • Reusability: If multiple components need the same logic, instead of copying and pasting, use an HOC.

  • Code Cleanup: Keeps your main components clean and focused only on UI.

  • Better Logic Handling: Perfect for handling authentication, permissions, logging, etc.

🔥Basic Example: Adding a Title to Any Component

🧔Without HOC (Bad Approach)

Let’s say you have multiple pages (Home, About), and each needs a title. Instead of writing the same title logic in every component, you can use an HOC (Higher Order Component).

function Home() {
    return <h2>Welcome to Home Page</h2>;
}

function About() {
    return <h2>About Us</h2>;
}

🅿️Problem?
If we want to add a title dynamically, we’ll have to modify every component separately. Here, there are only two, but it can be 10, 20, 100 and more.

💯Using HOC (Smart Approach)

We’ll create an HOC that wraps any component and adds a title dynamically!

1️⃣Step 1: Create an HOC Function

function withTitle(Component, title) {
    return function EnhancedComponent() {
        return (
            <div>
                <h1>{title}</h1>
                <Component />
            </div>
        );
    };
}
  • It accepts a component (Component) and a title (title) as arguments.

  • It returns a new component that displays the title + the original component.

2️⃣Step 2: Use HOC with Components

const HomeWithTitle = withTitle(Home, "Home Page");
const AboutWithTitle = withTitle(About, "About Us");

function App() {
    return (
        <div>
            <HomeWithTitle />
            <AboutWithTitle />
        </div>
    );
}

export default App;

🏆 Benefits of HOC Here

✅ We didn’t modify Home or About, but they magically got titles!
✅ If we want to change the title, we just update the HOC.


🔥 Advanced Example: Protecting Routes with HOC

Let's say you want to protect some pages (like Dashboard) so that only logged-in users can see them.

1️⃣Step 1: Create an HOC for Authentication

function withAuth(Component) {
    return function ProtectedComponent() {
        const isLoggedIn = localStorage.getItem("user"); // login check

        if (!isLoggedIn) {
            return <h2>Access Denied! Please Log In.</h2>;
        }

        return <Component />;
    };
}
  • It checks if the user is logged in.

  • If not logged in, it blocks the page.

  • If logged in, it renders the original component.

2️⃣Step 2: Protect the Dashboard

function Dashboard() {
    return <h2>Welcome to Dashboard</h2>;
}

const ProtectedDashboard = withAuth(Dashboard);
  • We wrapped the Dashboard inside withAuth, so it only loads if the user is logged in.

3️⃣Step 3: Use It in App

function App() {
    return (
        <div>
            <ProtectedDashboard />
        </div>
    );
}

export default App;

🏆 Why This is Powerful?

No need to repeat login checks everywhere.
✅ We can secure any page by simply wrapping it with withAuth().
✅ Code is clean & reusable!

💭Final Thoughts - When to Use HOC?

✅ Use HOC When...❌ Don’t Use HOC When...
You repeat the same logic across componentsYou need to modify only one component
You want to add authentication, logging, or analyticsYou have simple, one-time-use logic
You want to enhance components dynamicallyReact Hooks (useEffect, useContext) can handle it better

🚀Conclusion

1️⃣ HOC is like a tree🌳 that grows another tree inside it and returns it (it takes a component, enhances it, and returns it).
2️⃣ It helps in reusability, better logic management, and keeping components clean.
3️⃣ You can use it for adding titles, protecting routes, logging, analytics, and more.

0
Subscribe to my newsletter

Read articles from Aniruddha Lal Verma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aniruddha Lal Verma
Aniruddha Lal Verma