A Higher-Order Component is a function that takes a component and returns an enhanced component with additional props or behavior; they're less common now because React Hooks provide a cleaner solution for logic reuse without wrapper components.
What is an HOC?
Common Use Cases:
withAuth)withLoading)withData)withTheme)withTracking)Problems with HOCs:
React.forwardRefWhy Hooks are Preferred:
When HOCs Still Make Sense:
// HOC that adds loading state
function withLoading(WrappedComponent) {
// Return a new component
return function WithLoadingComponent({ isLoading, ...props }) {
if (isLoading) {
return <div className="spinner">Loading...</div>;
}
return <WrappedComponent {...props} />;
};
}
// Usage
const UserListWithLoading = withLoading(UserList);
function App() {
const [loading, setLoading] = useState(true);
const [users, setUsers] = useState([]);
return (
<UserListWithLoading
isLoading={loading}
users={users}
/>
);
}