How to use Higher-Order Components in React ?
Last Updated :
24 Apr, 2025
Higher-Order Component is an advanced function, which reuses component logic in a React Component and returns an enhanced new component. It wraps commonly used processes to allow their use by different components, such as state modification or props change. Components are wrapped in HOCs, whose goal is to improve them without changing their original constructions. In React applications, they serve code reusability and abstraction purposes. To compose related components, HOCs are powerful tools.
Reasons to use Higher-Order Components:
- Code Reusability: Higher components encapsulate to reuse the common logic here. This we do across many components to reduce code duplication.
- Abstraction of Logic: Higher Order Component often removes the repetitive tasks. Such as data fetching or authentication. This makes our code to have more code readability.
- Composability: Several behaviors or features can be combined into single components using several HOCs hence providing granular control over component behavior and allowing for the creation of sophisticated UIs.
Approach to Create a Higher-Order Component:
- Traditional Higher-Order Components (HOCs): This method is a bit different in that you create a function which takes a component as its argument and then returns an enhanced version of that component. The HOC wraps common logic like data fetching or authentication around the wrapped component.
- Render Props: In this case, the key difference between using render props instead of HOC is that the former introduces a function prop on it so that it can share code or state with other components. Comparing to HOCs Render Props are more flexible than they have greater composability property in some cases.
- Hooks: React has introduced hooks which let users write custom reusable hooks. For some use cases, hooks offer much shorter and easier to understand inter-component communication without resorting to more common HOC styled APIs being used today.
Higher-Order Component Structure:
Step 1: The Higher Order Component (HOC) function is defined as a function that takes a component as its input and returns a new component imbued with additional functionality.
const HigherOrderCompnent = (WrappedComponent) => {
// other code
}
Step 2: The creation of the new component involves defining a class component that wraps the WrappedComponent
and introduces supplementary functionality.
const NewComponent = (props) => {
// code
return (
// ...
);
};
Step 3: In the render()
method of NewComponent
, ensure the seamless passing of all props, including those added by the Higher Order Component (HOC), to the WrappedComponent
.
return <WrappedComponent {...props} additionalProp={additionalProp} />;
Step 4: To complete the Higher Order Component (HOC) function, ensure it returns the NewComponent
so that it can be seamlessly integrated into the application.
const HigherOrderCompnent
= (WrappedComponent) => {
const NewComponent = (props) => {
// other code
};
return NewComponent;
};
When to Use HOCs in your React Code:
Authentication:
In the context of an application featuring multiple routes, where certain routes demand user authentication, a more efficient approach involves the creation of a Higher Order Component (HOC) named withAuth
. This HOC, encapsulating the authentication logic, verifies the user's authentication status and redirects them to the login page if necessary. By employing this withAuth
HOC, the need for duplicating authentication logic in individual components or routes is eliminated, ensuring consistent and streamlined authentication behavior throughout the application.
Logging:
In scenarios where consistent functionality, such as authentication checks or logging, is needed across specific components, creating Higher Order Components (HOCs) like withAuth
or withLogger
centralizes and simplifies the implementation, reducing redundancy and ensuring uniform behavior.
Styling and Theming:
For efficient styling and theming in a design system, consider using the Higher Order Component (HOC) withTheme
. This HOC provides theme-related props to components, ensuring easy access and application of consistent styles based on the specified theme.
Steps to Create Higher-Order Components in React:
Step 1: Setting up the React Project:
npx create-react-app hoc
Step 2: After creating your project folder, move to it using the following command.
cd hoc
Example: Below is an Example of creating a High-Order Componet.
JavaScript
import React from 'react';
// Define the Higher-Order Component
const withLoading = (WrappedComponent) => {
return function WithLoadingComponent(props) {
const [loading, setLoading] = React.useState(false);
React.useEffect(() => {
// Simulate loading data
setLoading(true);
const timer = setTimeout(() => {
setLoading(false);
}, 2000);
return () => clearTimeout(timer);
}, []);
// Pass loading state as a prop to the wrapped component
return <WrappedComponent
{...props} loading={loading} />;
};
};
// Define a component to be enhanced (functional component)
const MyComponent = ({ loading }) => (
<div>
{loading ? <p>Loading...</p> :
<p>Data Loaded Successfully!</p>}
</div>
);
// Enhance the component with the HOC
const EnhancedComponent = withLoading(MyComponent);
function App() {
return (
<>
{/* Render the enhanced component */}
<EnhancedComponent />
</>
);
}
export default App;
Output:
Hoc Change
Conclusion:
In Conclusion, Higher Order Components offers a various range of powerful ways of reusing the functionality of the React Components. Showed various different approaches and followed the steps , which everyone can follow to take Higher Order Components in their React Applications, leading to more scalable, maintainable, and efficient codebases.
Similar Reads
ReactJS Higher-Order Components
Higher-order components (HOC) are an advanced technique in React that is used for reusing component logic. It is the function that takes the original component and returns the new enhanced component.It doesnât modify the input component directly. Instead, they return a new component with enhanced be
5 min read
How to use Popper Component in ReactJS ?
A Popper is used to show the part of the content on top of another. It's an alternative feature for react-popper. Material UI for React has this component available for us, and it is simple and very easy to integrate. For perfect positioning, it uses 3rd party library which is Popper.js.Prerequisite
3 min read
How to use Paper Component in ReactJS ?
In Material Design, the physical properties of paper are translated to the screen. Material UI for React has this component available for us and it is very easy to integrate. We can use the Paper Component in ReactJS using the following approach. Prerequisites:React JSMaterial UIApproachTo use Paper
2 min read
How to use Portal Component in ReactJS ?
The portal component renders its children into a new subtree outside the current DOM hierarchy. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Portal Component in ReactJS using the following approach.Prerequisites:NodeJS or NPMReact JSMate
2 min read
How to use List Component in ReactJS?
Lists are continuous, vertical indexes of text or images. Material UI for React has this component available for us, and it is very easy to integrate. We can use the List Component in ReactJS using the following approach. Prerequisites:NodeJS or NPMReactJSSteps to Create the React Application And In
2 min read
Why would you use a Higher-Order Component in React ?
A Higher-Order Component (HOC) in React is used to share common functionality between multiple components. It's like a function that takes a component as an argument and returns a new enhanced component with added features. By offering a pattern for reusing component logic, HOCs help in crafting mor
3 min read
How to use CssBaseLine Component in ReactJS ?
In React JS, A CssBaseline component is a collection of HTML elements and attribute style-normalizations. At the <head> of our document, it is added as CSS reset. This component is used to add some basic styling to our application like box-sizing, background color, etc like CSS reset for our a
3 min read
How to use HOCs to reuse Component Logic in React ?
In React, making reusable components keeps your code neat. Higher-order components (HOCs) are a smart way to bundle and reuse component logic. HOCs are like magic functions that take a component and give you back an upgraded version with extra powers or information. HOCs can be implemented in a few
4 min read
How to create components in ReactJS ?
Components in React JS is are the core of building React applications. Components are the building blocks that contains UI elements and logic, making the development process easier and reusable. In this article we will see how we can create components in React JS. Table of Content React Functional C
3 min read
How to Pass JSON Values into React Components ?
In React, you can pass JSON values into components using props. Props allow us to send data from a parent component to its child components. When rendering a component, you can pass the JSON values as props. These props can then be accessed within the componentâs function or class, allowing you to d
3 min read