DA

dev Await

February 2025

Higher Order Components in React: From Zero to Hero 🚀

Hey there! 👋 Are you confused about Higher Order Components in React? Don't worry! Let's break it down in the simplest way possible.

What is a Higher Order Component? 🤔

Imagine you have a Christmas gift box that can wrap any gift and add a bow on top. That's exactly what a Higher Order Component does - it wraps your React component and adds something extra to it!

The Simplest Example Ever 🎁

Let's say we have a simple component that shows a message:

// Our simple message component
function Message({ text }) {
  return <div>{text}</div>;
}

Now, what if we want to add a blue border around it? We could create a HOC:

// This is our HOC - it adds a blue border
function withBlueBorder(Component) {
  return function NewComponent(props) {
    return (
      <div style={{ border: '2px solid blue', padding: '10px' }}>
        <Component {...props} />
      </div>
    );
  }
}

// Now let's use it
const MessageWithBorder = withBlueBorder(Message);

That's it! Now you can use it like this:

// This will show your message with a blue border
<MessageWithBorder text="Hello World!" />

A Real Example You'll Actually Use 📱

Let's create something more useful - a loading screen:

function withLoading(Component) {
  return function LoadingWrapper(props) {
    // If loading is true, show "Loading..."
    if (props.loading) {
      return <div>Loading...</div>;
    }

    // If not loading, show the normal component
    return <Component {...props} />;
  }
}

// Your normal component
function UserProfile({ name, email }) {
  return (
    <div>
      <h2>{name}</h2>
      <p>{email}</p>
    </div>
  );
}

// Add loading feature to UserProfile
const UserProfileWithLoading = withLoading(UserProfile);

Now you can use it like this:

// This will show "Loading..." while your data is loading
<UserProfileWithLoading 
  loading={true}
  name="John" 
  email="john@example.com" 
/>


When Should You Use HOCs? 🎯

Use HOCs when you want to:

  • Add the same feature to many components

  • Show a loading screen

  • Check if users are logged in

  • Add styles to multiple components

Simple Rules to Remember 📝

  1. HOCs are just wrapper functions

  2. They take a component and return a new one

  3. The name should start with 'with' (like withLoading, withBorder)

  4. They can add new features to your component

That's It! 🎉

Remember:

  • HOCs are just wrappers that add extra features

  • They're like gift wrapping for your components

  • Start with simple HOCs and practice

Level up your React skills with DevAwait! 🚀

devawait.png

Copyright © 2025 DevAwait. All rights reserved.