Higher-Order Components (HOCs) are a design pattern in React that allows you to wrap existing components with additional functionality without modifying their code.
To create a Higher-Order Component (HOC), follow these steps:
WrappedComponent
) as an input parameter.import React from 'react';
// HOC that adds an extra prop
const withExtraProps = (WrappedComponent) => {
return (props) => <WrappedComponent {...props} extraProp="value" />;
};
// Component to be wrapped
const MyComponent = (props) => {
return <div>Extra prop: {props.extraProp}</div>;
};
// Enhanced version of MyComponent
const EnhancedComponent = withExtraProps(MyComponent);
// Usage
const App = () => {
return <EnhancedComponent />;
};
HOCs are useful for:
withAuth
, withLogger
)In modern React codebases, Custom Hooks are often preferred for logic reuse. However, understanding HOCs is still essential for working with legacy code and some libraries.
HOCs are a powerful abstraction for sharing logic between components in React. They promote code reuse, composability, and separation of concerns, but should be used judiciously to avoid complexity.