Overview
What is a Higher-Order Component?
- Takes a component as input
- Returns a new component with extended functionality
HOC Example
const withSomething = (Component) => {
return (props) => <Component {...props} />;
};
Building a withLogger HOC
- When the component mounts
- When it unmounts
- When it updates
- What props are passed
Step 1: The Base Component
Base Component
type UserProps = {
name: string;
};
function UserCard({ name }: UserProps) {
return <div>Hello, {name}!</div>;
}
Step 2: Create the 'withLogger' HOC
withLogger HOC
import { useEffect } from 'react';
function withLogger<P>(WrappedComponent: React.ComponentType<P>) {
const ComponentWithLogger = (props: P) => {
useEffect(() => {
// Log data on component mount
console.log(`Component ${WrappedComponent.name} mounted.`);
return () => {
// Log data on component unmount
console.log(`Component ${WrappedComponent.name} unmounted.`);
};
}, []);
console.log(`[Logger] Props:`, props);
return <WrappedComponent {...props} />;
};
ComponentWithLogger.displayName = `withLogger(${WrappedComponent.displayName || WrappedComponent.name})`;
return ComponentWithLogger;
}
- mount, unmount logs
- Generic props type inference
- Named component for DevTools
Step 3: Use the HOC
Using the HOC
const UserCardWithLogger = withLogger(UserCard);
function App() {
const [name, setName] = useState("Alice");
return (
<div>
<UserCardWithLogger name={name} />
<button onClick={() => setName("Bob")}>Change Name</button>
</div>
);
}
Console Output
Component UserCard mounted.
[Logger] Props: { name: 'Alice' }
Component UserCard updated.
[Logger] Props: { name: 'Bob' }
Component UserCard unmounted.
Why Use HOCs for Logging?
- Easy to apply across components
- Non-invasive (original component logic stays pure)
- Supports both class and function components
- Great for debugging, analytics, performance tracking
Real-World Use Cases
- 🔐 withAuth – redirect if not authenticated
- 📊 withTracking – send metrics to analytics
- 🚀 withFeatureFlag – hide/show features
- 🛠️ withErrorBoundary – wrap with error fallback
Recap
- Mount
- Update
- Unmount
- Props on every render