DEV Community

Emdadul Haque
Emdadul Haque

Posted on

How to Use a Higher-Order Component (HOC) the Right Way in React

What is a HOC?

A Higher-Order Component is a function that:

  • Takes a React component as input
  • Returns a new React component with extra features

Example of a HOC

const withAdminRole = (WrappedComponent) => {
  // takes a component as argument and returns new component
  return (props) => <WrappedComponent {...props} role="admin" />;
};

const WelcomeUser = ({ name, role }) => {
  return <p>Welcome, {name}! Your role is: {role}</p>;
};

Enter fullscreen mode Exit fullscreen mode

❌ Inefficient Way to Use It

// Don't do this
const UserWithRole = () => withAdminRole(WelcomeUser);

<UserWithRole name="Apu" />;
Enter fullscreen mode Exit fullscreen mode

What’s wrong here?

  • withAdminRole(WelcomeUser) is called every time <UserWithRole /> renders
  • This creates a new component on every render
  • React can’t optimize this
  • It can cause unnecessary re-renders

✅ Efficient Way to Use It

// Do this instead
const UserWithRole = withAdminRole(WelcomeUser);

<UserWithRole name="Apu" />;
Enter fullscreen mode Exit fullscreen mode

What’s right here?

  • withAdminRole(WelcomeUser) is called only once,
  • UserWithRoleis now a stable component
  • React can optimize performance
  • Your code is cleaner and safer

Simple Rule

Always assign the result of a HOC to a constant. Don’t call the HOC inside a component or inside render.

Top comments (0)