React
Higher-Order Components
Component enhancement pattern.
By EZ4Code Team
reacthoc
Code
import { useState, useEffect } from 'react';
// Auth HOC
function withAuth(WrappedComponent) {
return function AuthComponent(props) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const token = localStorage.getItem('token');
if (!token) {
window.location.href = '/login';
return;
}
fetch('/api/me', {
headers: { Authorization: `Bearer ${token}` }
})
.then(res => res.json())
.then(data => { setUser(data); setLoading(false); });
}, []);
if (loading) return <div>Loading...</div>;
if (!user) return null;
return <WrappedComponent {...props} user={user} />;
};
}
// Logging HOC
function withLog(WrappedComponent) {
return function LogComponent(props) {
useEffect(() => {
console.log('Mounted:', WrappedComponent.name);
return () => console.log('Unmounted:', WrappedComponent.name);
}, []);
return <WrappedComponent {...props} />;
};
}
// Compose multiple HOCs
const EnhancedDashboard = withLog(withAuth(Dashboard));
// Usage
function Dashboard({ user }) {
return <h1>Welcome, {user.name}</h1>;
}
export default withAuth(Dashboard);
// HOC caveats:
// 1. Don't use HOCs in render
// 2. Static methods must be copied
// 3. ref won't pass through (use forwardRef)Explanation
Higher-Order Components take a component and return an enhanced component, used for logic reuse; multiple HOCs can be composed.
More React Snippets
Controlled Form with Validation
Build a controlled React form with inline validation and error messages.
Event Handling and List Rendering
Handle events and render dynamic lists with keys in React.
useState
State management Hook.
useEffect
Side-effect Hook.
useContext
Shared state via context.
useReducer
Complex state management.