Member-only story
Uncommon but Very Useful Higher-Order Components (HOCs) in React
Higher-Order Components (HOCs) are an advanced technique in React for reusing component logic. They’re functions that take a component and return a new component, wrapping behavior around it. HOCs can be incredibly powerful but are often under utilized because they are overshadowed by hooks or misunderstood. In this article, we’ll dive into some less common but extremely useful HOCs that can streamline your React development.
withErrorBoundary
React introduced error boundaries to catch Javascript errors anywhere in the component tree. A common implementation pattern is wrapping components in an ErrorBoundary component. But what if you could avoid adding this manually every time?
Enter the withErrorBoundary
HOC.
Implementation
import React, { useState, useEffect } from 'react';
const withErrorBoundary = (WrappedComponent, FallbackComponent) => {
return function ErrorBoundaryWrapper(props) {
const [hasError, setHasError] = useState(false);
useEffect(() => {
const handleError = (error, errorInfo) => {
console.log('Error caught by HOC:', error, errorInfo);
setHasError(true);
};
const originalErrorHandler = window.onerror;
window.onerror = handleError;
return () => {
window.onerror = originalErrorHandler;
};
}, []);
if (hasError) {
return <FallbackComponent />;
}
return <WrappedComponent {...props}…