Think of HOCs as decorators or wrappers. They take a component and return a powerful, upgraded version of it.
This is the standard pattern. We wrap the returned component to handle the loading state automatically.
// The HOC Function
function withLoader(WrappedComponent) {
// Returns a New Component
return function EnhancedComponent(props) {
const [isLoading, setIsLoading] = useState(true);
// Shared Logic
useEffect(() => {
setTimeout(() => setIsLoading(false), 2000);
}, []);
if (isLoading) return <Spinner />;
// Pass through original props!
return <WrappedComponent {...props} />;
};
}// 1. Create Base Component
const UserProfile = ({ name }) => <h1>Hello, {name}</h1>;
// 2. Wrap it
const UserWithLoader = withLoader(UserProfile);
// 3. Use the Enhanced Component
<UserWithLoader name="Alice" />Here, the HOC inspects the user and injects an `isAdmin` prop. The wrapped component doesn't need to check auth logic itself; it just receives the result!
function withAuth(WrappedComponent) {
return function(props) {
const user = useUser(); // Hook to get current user
// 1. Check permissions
const isAdmin = user.role === 'ADMIN';
// 2. Inject new prop
return (
<WrappedComponent
{...props}
isAdmin={isAdmin}
/>
);
};
}HOCs are just the beginning. Check out Render Props and Custom Hooks to complete your mastery.
Explore React Patterns