How do Higher-Order Components (HOCs) work in React?
· Category: React
Short answer
A Higher-Order Component is a function that takes a component and returns a new component with additional props or behavior.
How it works
HOCs wrap a component to inject data, handle logic, or modify behavior. Common examples include authentication checks, data fetching, and theming.
Example
function withLoading(WrappedComponent) {
return function WithLoadingComponent({ isLoading, ...props }) {
if (isLoading) return <p>Loading...</p>;
return <WrappedComponent {...props} />;
};
}
const UserProfile = withLoading(function UserProfile({ user }) {
return <div>{user.name}</div>;
});
Tips
- Do not mutate the original component; compose it.
- Copy static properties and forward refs to preserve the wrapped component's interface.
- Consider custom hooks as a simpler alternative before introducing an HOC.
- Be aware of prop name collisions when composing multiple HOCs.