Higher-Order Components (HOCs) in React
Suresh Kumar Rajendran
Head of R&D | Building Framework for ERP product | .Net | C# | SQL | React | Kendo | JavaScript| PMO | Construction Domain ERP | Initiation of AI based ERP
What is a Higher-Order Component (HOC)?
A Higher-Order Component (HOC) is a function that takes a component and returns a new enhanced component. It allows for code reuse, logic abstraction, and component composition in React.
?? Definition
A Higher-Order Component is a pattern used to share common logic across multiple components by wrapping them inside a function.
Why Use Higher-Order Components?
How to Create a Higher-Order Component
An HOC is just a function that takes a component as an argument and returns a new component with additional props or logic.
Basic Example of an HOC
javascript
import React from 'react';
// Higher-Order Component function
function withBackgroundColor(WrappedComponent) {
? return function EnhancedComponent(props) {
??? return (
????? <div style={{ backgroundColor: 'lightblue', padding: '10px' }}>
??????? <WrappedComponent {...props} />
????? </div>
??? );
? };
}
?
// Simple Component
function Message(props) {
? return <h2>{props.text}</h2>;
}
?
// Using HOC
const MessageWithBackground = withBackgroundColor(Message);
function App() {
? return <MessageWithBackground text="Hello from HOC!" />;
}
?
export default App;
?? What’s Happening Here?
Common Use Cases for HOCs
领英推荐
Example: HOC for Authentication
javascript
import React from 'react';
?
// Higher-Order Component for Authentication
function withAuth(WrappedComponent) {
? return function AuthComponent(props) {
??? const isAuthenticated = true; // Example authentication check
??? if (!isAuthenticated) {
????? return <h2>Please log in to continue.</h2>;
??? }
??? return <WrappedComponent {...props} />;
? };
}
?
// Regular Component
function Dashboard() {
? return <h2>Welcome to the Dashboard!</h2>;
}
// Wrapping with HOC
const ProtectedDashboard = withAuth(Dashboard);
?
function App() {
? return <ProtectedDashboard />;
}
export default App;
?? How It Works:
HOCs vs Render Props vs Hooks
?? HOCs add an extra layer of components, which can cause "wrapper hell". React Hooks (useEffect, useState) are often preferred today for cleaner logic sharing.
Best Practices for Using HOCs
Conclusion
Higher-Order Components are a powerful pattern in React for reusing component logic. They work well for tasks like authentication, logging, and styling. However, with the introduction of React Hooks, many use cases for HOCs can now be handled with useEffect and useContext, making the code more readable and maintainable.