Higher Order Components
Higher Order Components
Higher-order components are a design pattern in React where a function takes a component as an
argument and returns an enhanced new component.
In simpler terms, HOCs are functions that wrap existing components, providing them with additional
props or behaviors.
The main benefit of HOCs is that they enable us to extend the functionality of multiple components
without repeating the same code in each of them. This promotes code reuse and enhances the
maintainability of your React applications.
Reusability: HOCs allow you to encapsulate shared functionalities and apply them to multiple
components, promoting code reuse.
Separation of Concerns: HOCs help maintain separate responsibilities, enabling your components to
focus on their specific tasks.
Code Abstraction: HOCs abstract common logic from components, making them more concise and
easier to understand.
Composability: You can combine various HOCs to compose complex functionalities into your
components.
Example Code:
HOCex.js
function HOCex() {
return (
<>
<Counterclick/>
<Counterhover/>
</>
);
}
Explanation:
HOCex.js is the main component that renders two components: Counterclick and Counterhover.
Both of these components utilize the HOC pattern to manage and share state logic.
CounterHandler.js
function CounterHandler(BaseComponent) {
const NewComponent = () =>{
const [count, setCount] = useState(0);
return NewComponent;
}
Explanation:
CounterHandler.js is a Higher Order Component (HOC) that adds counting functionality to any base
component.
Description: This HOC adds state and functionality for counting to the provided BaseComponent.
NewComponent: A new component that wraps the BaseComponent and provides it with count and
incrementCount props.
CounterClick.js
function Counterclick(props) {
return (
<>
<p>Click Counts: {props.count}</p>
<button onClick={props.incrementCount}>
Increment
</button>
</>
);
}
Explanation:
Description: This component displays the current count and a button to increment the count.
Counterhover.js
function Counterhover(props) {
return (
<>
<p>Hover Counts: {props.count}</p>
<button onMouseOver={props.incrementCount}>
Increment
</button>
</>
);
}
Explanation:
Counterhover.js is a component that displays the number of times a button is hovered over.
Description: This component displays the current count and a button to increment the count when
hovered over.