DEV Community

Cover image for 🧙‍♂️ The Magic Wrapper: Understanding HOCs in React (For Beginners)
Werliton Silva
Werliton Silva

Posted on

🧙‍♂️ The Magic Wrapper: Understanding HOCs in React (For Beginners)

Once upon a time, there was a young developer named Tchaca. He loved building fun things with React – like buttons that blinked, forms that sent messages, and pages that showed dragon profiles!

But one day, Tchaca ran into a problem...

😫 “Why am I copying the same code into so many components?! I keep writing the same login checks, loading states, and error handling. It’s driving me crazy!”

Just then, the Fairy of Reusable Code appeared and whispered:

🧚‍♀️ “Tchaca, what you need is a magic trick called a Higher-Order Component, or HOC! It lets you wrap your components and give them superpowers - without changing how they work!”

🧩 What Is a Higher-Order Component?

A Higher-Order Component (HOC) is like a magic wrapper.

It takes a regular component - like a Button or a Profile - and returns a new component that has extra powers (like checking if someone is logged in, or showing a loading spinner).

Here’s what the spell looks like:

function withMagicPower(WrappedComponent) {
  return function EnhancedComponent(props) {
    // Add your magic (extra logic) here
    return <WrappedComponent {...props} />;
  };
}
Enter fullscreen mode Exit fullscreen mode

💡 Tchaca’s First Spell: Logging When a Component Appears

Tchaca wanted to see when components were shown on the screen. So he made a wrapper:

function withLogging(WrappedComponent) {
  return function EnhancedComponent(props) {
    React.useEffect(() => {
      console.log("Component appeared!");
    }, []);

    return <WrappedComponent {...props} />;
  };
}
Enter fullscreen mode Exit fullscreen mode

Now, whenever he wrapped a component with withLogging, it would log a message!

🔒 Tchaca’s Next Spell: Only Show Stuff If Logged In

function withAuthentication(WrappedComponent) {
  return function EnhancedComponent({ isAuthenticated, ...props }) {
    if (!isAuthenticated) {
      return <p>You must be logged in!</p>;
    }
    return <WrappedComponent {...props} />;
  };
}
Enter fullscreen mode Exit fullscreen mode

He used it like this:

const SecretButton = withAuthentication(Button);

// Then used it in his app:
<SecretButton 
isAuthenticated={true} 
onClick={doSomething}>
Click Me
</SecretButton>
Enter fullscreen mode Exit fullscreen mode

🧪 Be Careful With Spells!

  1. Don't cast spells inside other components.

    Always create your HOC outside of render functions, or React might forget the old state.

  2. Pass all props properly!

    Don’t forget to use {...props} or things might stop working.

  3. Refs are special!

    If you use ref, your HOC needs to use React.forwardRef to work correctly.


🎓 The Lesson

Tchaca learned that Higher-Order Components are like reusable spells. Instead of repeating the same logic again and again, he could wrap his components and give them powers like logging, authentication, or data loading.

And with great power comes... way cleaner code! 🧼✨


Which magic spell (HOC) will you try in your next React adventure? 🧙‍♂️


Refs:

Top comments (0)