How to use HOCs to reuse Component Logic in React ?
Last Updated :
27 Mar, 2024
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 different ways, depending on the requirements in the following ways:
1. Function that Returns a Function: This is the most common approach where the HOC is a function that accepts a component and returns a new component that renders the original component with enhanced props.
Syntax:
const withData = (WrappedComponent) => (props) => {
// Enhanced logic here
return <WrappedComponent {...props} />;
};
2.Using ES6 Classes: Sometimes, you might need the HOC to maintain its own state or lifecycle methods. In such cases, extending React.Component in the HOC can be beneficial.
Syntax:
const withSubscription = (WrappedComponent, selectData) => {
return class extends React.Component {
// Implement lifecycle methods and state here
render() {
return <WrappedComponent {...this.props} />;
}
};
};
Steps to Create Application (Install Required Modules)
Step 1: Initialize a new React project: If you haven’t already, create a new React app by running:
npx create-react-app my-app
Step 2: Navigate into your project:
cd my-app
Step 3: Install any additional dependencies you might need, depending on your project requirements. For general purposes, the React app setup comes with everything you need to get started.
the updated dependencies in package.json file will look like:
"dependencies": {
"@reduxjs/toolkit": "^2.2.1",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^9.1.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
Approach 1: Function that Returns a Function
This approach is useful for adding simple enhancements or props to a component. It's the most straightforward way to implement an HOC.
Example: Below is the code example using `withExtraProps`:
JavaScript
import React from 'react';
// withExtraProps HOC adds additional props to the wrapped component
const withExtraPrimport React from "react";
// withExtraProps HOC adds additional props to the wrapped component
const withExtraProps = (WrappedComponent) => (props) => {
const extraProps = { extraProp: "This is an extra prop!" };
return <WrappedComponent {...props} {...extraProps} />;
};
// Simple component that displays props
const DisplayPropsComponent = (props) => (
<div>
<h1>
{Object.entries(props).map(([key, value]) => (
<p key={key}>{`${key}: ${value}`}</p>
))}
</h1>
</div>
);
// Enhanced component with extra props
const EnhancedComponent = withExtraProps(DisplayPropsComponent);
// Usage in App component
function App() {
return <EnhancedComponent someProp="This is some prop" />;
}
export default App;
ops = (WrappedComponent) => (props) => {
const extraProps = {extraProp: 'This is an extra prop!'};
return <WrappedComponent {...props} {...extraProps} />;
};
// Simple component that displays props
const DisplayPropsComponent = (props) => (
<div>
<h1>
{Object.entries(props).map(([key, value]) => (
<p key={key}>{`${key}: ${value}`}</p>
))}
</h1>
</div>
);
// Enhanced component with extra props
const EnhancedComponent = withExtraProps(DisplayPropsComponent);
// Usage in App component
function App() {
return <EnhancedComponent someProp="This is some prop" />;
}
export default App;
Output:
Approach 1 OutputApproach 2: Using ES6 Classes
When you need the HOC to have its own state or lifecycle methods, using ES6 classes is the preferred approach.
Example: Below is the code example `withLoadingIndicator`
JavaScript
import React from "react";
// withLoadingIndicator HOC shows a loading
// indicator based on its own state
const withLoadingIndicator = (WrappedComponent) => {
return class extends React.Component {
constructor(props) {
super(props);
this.state = { isLoading: true };
}
componentDidMount() {
// Mock loading time
setTimeout(() => this.setState({ isLoading: false }),1000);
}
render() {
const { isLoading } = this.state;
return isLoading ? (
<div>Loading...</div>
) : (
<WrappedComponent {...this.props} />
);
}
};
};
// Component to be enhanced
const HelloWorld = () => <div>Hello, world!</div>;
// Enhanced component with loading indicator
const HelloWorldWithLoading = withLoadingIndicator(HelloWorld);
// Usage in App component
function App() {
return <HelloWorldWithLoading />;
}
export default App;
Output:
Approach 2 Output
Similar Reads
How to use Higher-Order Components in React ?
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
5 min read
How to Integrate Redux with React Components ?
Redux is an open-source JavaScript library for managing and centralizing application state. It helps you to write applications that behave consistently and are easy to test and run in different environments. It can also be understood as the predictable state container for the JavaScript app. It is m
4 min read
How to make Reusable React Components ?
ReactJS is a JavaScript library used to build single-page applications (SPAs). React makes it easy to create an interactive user interface by using a component-based approach. In this article, we will learn about Reusable React Components with examples. Table of Content What are Reusable React Compo
4 min read
How to connect the components using Connect() in React Redux
In React Redux, you use the connect() function to connect your components to the Redux store. This function takes two parameters: mapStateToProps and mapDispatchToProps. mapStateToProps maps the store's state to the component's props, while mapDispatchToProps maps dispatch actions to props. By using
3 min read
How to use Switch Statement Inside a React Component?
When the switch statement is used within a React component it can greatly improve the readability and structure of the code. The logic of a switch statement can be clear and concise. This avoids complex and difficult nested if-else blocks. This leads to more maintainable and better-organized code. I
3 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 Map Data into Components using ReactJS?
Mapping data in react js component is a comman practice to render the lists and repeating elements. In this article, we will have a users data and we will map it to react components to display the users information in the react appPrerequisites:React JSNodejs and npmJavaScript Array mapApproachTo ma
3 min read
How to use useMemo Hook in a Functional Component in React ?
In React development, optimizing performance is crucial for delivering responsive and fast user experiences. One way to achieve this is by using the `useMemo` hook. In this article, we'll explore what `useMemo` is, why it's beneficial, and how to use it effectively in functional components. Table of
3 min read
How to use PropTypes in a Functional Component in React?
PropTypes is a mechanism provided by React for type-checking props passed to components. It allows developers to specify the expected types of props (such as strings, numbers, arrays, objects, etc.) and whether they are required or optional. PropTypes helps catch bugs early by providing warnings in
2 min read
How to add Event Listeners to wrapped Component in ReactJS ?
React provides a powerful way of DOM manipulation by introducing the concept of virtual DOM. It is mainly used to build single-page applications. There are times when you need to add event listeners. This can be achieved by using the concept of forwarding refs and leveraging React's lifecycle method
2 min read