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>;
};
❌ Inefficient Way to Use It
// Don't do this
const UserWithRole = () => withAdminRole(WelcomeUser);
<UserWithRole name="Apu" />;
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" />;
What’s right here?
-
withAdminRole(WelcomeUser)
is called only once, -
UserWithRole
is 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)