HOC in React.js
The React.js application design pattern’s Higher Order Components (HOCs) use pure JavaScript functions to add reusable code and functionality to preexisting components. After receiving a component as an argument, a HOC returns a new component with expanded functionality that encapsulates the original component. Regardless of how differently those components may render, their main purpose is to promote code reusability and better organisation by sharing common logic, stateful behaviour, and side effects across several components.

By keeping components smaller and more concentrated on generating their user interface, this method aids in the separation of responsibilities. A HOC could be used, for example, to log component mounts or to apply authentication checks. HOCs became the preferred option for managing reusable functionality when React deprecated mixins. In essence, a HOC serves as a wrapper that provides additional data or behaviour to the “normal” component by rendering it with additional props.
What is a Higher-Order Component?
Higher-order components are functions that change components rather than being components in and of themselves. These are the main elements:
Input and Output: Props (short for ‘properties’) are usually used to handle input to a React component. Similar to attributes in regular HTML elements, props are arguments that you give to a JSX element. The user interface (UI) that a React component shows is its output. Elements are defined by components, which in turn call upon components. JSX (JavaScript XML), an HTML-like syntactic extension for JavaScript that lets you add HTML components right inside your JavaScript code, is commonly used to describe this output.
Pure Functions: Because HOCs don’t alter the input component or present behaviour, they are regarded as pure functions. They wrap the original component instead, changing its props or adding functionalities. The higher-order function is thus re-run using the updated data input in the event that the data changes.
Why Use Higher-Order Components?
Higher-Order Components (HOCs) in React use pure JavaScript functions to add reusable code and functionality to existing components. HOCs are used to share logic, stateful behaviour, and side effects across numerous components, regardless of how they render. This method increases code reuse and application organisation. By enclosing logic in a HOC, components can stay smaller and focus on user interface rendering, improving separation of responsibilities. After React deprecated mixins, HOCs became popular for reusable functions. When developing React, HOCs offer a number of noteworthy advantages:
Code Reusability: They minimise code duplication by enabling developers to exchange logic and functionality across several components. This is especially helpful when dealing with issues like data collecting, authentication, or logging, where different UI elements may share similar underlying logic.
Enhancement and Feature Addition: HOCs are able to give already-existing components new capabilities or functionalities. A HOC might add more props to a component, change the rendering logic, or subscribe it to outside data, for example.
Separation of Concerns: Splitting concerns in React is a key approach for organising code so that different application functions are separate. This modular architecture simplifies application development, maintenance, and scaling. The Single Responsibility Principle in React says that each component should handle only one function or issue.
Maintainability: HOCs are pure functions, therefore updating the returned component usually only involves data or logic changes.
How Higher-Order Components Work
A HOC’s mechanism entails:
Accepting a Component: The term “accepting a component” in React usually describes how one component uses or integrates another into its rendering logic or additional functionality. Props, the special children prop, and more complex patterns like Higher-Order Components (HOCs) are the main tools used to accomplish this.
Returning a New Component: Following that, a new React component is returned, usually a class component or a functional component that renders the old component inside.
Wrapping and Augmenting: This new element encloses the existing element. The functions that the HOC can carry out within this wrapper include:
Injecting Props: Injecting props in React passes data and methods from a parent component to its children. This is key to designing dynamic, interactive, and reusable React user interfaces. Props configure a component’s rendering and behaviour without requiring it to manage its own internal data.
Handling State/Logic: In order to give pertinent information or callbacks as props to the wrapped component, it must be able to handle its own internal state or logic.
Lifecycle Management: To carry out side effects or data fetching that benefit the wrapped component, class-based HOCs might employ lifecycle methods (such as componentDidMount).
Code Example:
A straightforward HOC that records a message to the console whenever the wrapped component mounts will serve as an example. This example illustrates how a HOC can modify a component’s internal structure while adding a behaviour to it.
import React, { Component } from 'react';
function hocLogger(ComposedComponent) {
return class extends Component {
componentDidMount() {
console.log(`[HOC Log]: The component <{ComposedComponent.name}> has been mounted!`);
}
render() {
return <ComposedComponent {...this.props} />;
}
};
}
function MyComponent({ message }) {
return (
<div className="bg-white p-6 rounded-lg shadow-md text-center">
<h3 className="text-xl font-bold text-gray-800">Hello from MyComponent!</h3>
<p className="mt-2 text-gray-600">{message}</p>
</div>
);
}
function App() {
const MyLoggedComponent = hocLogger(MyComponent);
return (
<div className="flex flex-col items-center justify-center min-h-screen bg-gray-100 p-4">
<div className="w-full max-w-md p-8 bg-blue-50 rounded-2xl shadow-xl text-center">
<h1 className="text-3xl font-extrabold text-blue-800 mb-8">
Higher-Order Component Demo
</h1>
<p className="mb-4 text-gray-700">
Open your browser's developer console (F12) to see the HOC in action!
</p>
{/* Render the new, enhanced component */}
<MyLoggedComponent message="I am wrapped by the hocLogger HOC." />
</div>
</div>
);
}
export default App;
Output:
Higher-Order Component Demo
Open your browser's developer console (F12) to see the HOC in action!
Hello from MyComponent!
I am wrapped by the hocLogger HOC.
You will see “Hey, we are mounted!” logged to your browser’s console when the componentDidMount method within the HOC runs when MyLoggedComponent (now the upgraded version supplied by hocLogger) is rendered in a React.js application. There is no logging logic in the original MyLoggedComponent itself, showing how the HOC adds behaviour outside.
Reusable component logic can be effectively abstracted using HOCs. With libraries like Redux, they become a very popular method for handling global state by employing a connect function that serves as a HOC. Their usage in third-party libraries is common. Even now React Hooks have made it possible to reuse stateful functionality directly within functional components in new ways, HOCs are still a useful pattern, particularly for class components or for encapsulating pre-existing components with common capabilities.