Higher Order Components (HOCs) are a pattern in React for reusing component logic. HOCs are functions that take a component as an input and return a new enhanced component with additional props or behavior. This pattern was popular before hooks were introduced and is still useful for cross-cutting concerns like logging, authentication, and more.
Below is a simple component wrapped with a logging HOC. Check your browser console to see the log messages when the component mounts, receives props, and updates.
// withLogging.tsx
import React, { ComponentType, useEffect } from "react";
// Higher Order Component that adds logging
export function withLogging<P extends object>(
WrappedComponent: ComponentType<P>
) {
// Return a new component with the same props
const WithLogging = (props: P) => {
useEffect(() => {
// Log when component mounts
console.log(`[Logging HOC] ${WrappedComponent.displayName || WrappedComponent.name || 'Component'} mounted`);
// Log when component will unmount
return () => {
console.log(`[Logging HOC] ${WrappedComponent.displayName || WrappedComponent.name || 'Component'} will unmount`);
};
}, []);
// Log props on each render
console.log(`[Logging HOC] ${WrappedComponent.displayName || WrappedComponent.name || 'Component'} rendered with props:`, props);
// Render the wrapped component with its props
return <WrappedComponent {...props} />;
};
// Set a display name for better debugging
WithLogging.displayName = `WithLogging(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;
return WithLogging;
}
// Usage:
// const EnhancedComponent = withLogging(MyComponent);