ReactJS Higher-Order Components Last Updated : 24 Apr, 2025 Comments Improve Suggest changes Like Article Like Report 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 behavior.They allow you to reuse component logic across multiple components without duplicating it.They are pure functions that accept a component and return a new component.Syntax:const EnhancedComponent = higherOrderComponent(OriginalComponent);In this syntax:higherOrderComponent is a function that takes an existing component (OriginalComponent) as an argument.It returns a new component (EnhancedComponent) with additional functionality or behavior.The EnhancedComponent behaves like the original component but with enhanced features provided by the HOC.Implementation of the Higher-Order ComponentsStep 1: Create a React application Create a React application by using the following command.npm create vite@latest foldernamewhere foldername is the name of your project. You can change it to any name you prefer.npm create vite@latest foldername: This command initializes a new Vite project with a React template. Replace foldername with your desired project name.Step 2: Move in the FolderAfter creating your project folder i.e. foldername, move to it using the following command.cd foldernameProject Structure:Project StructureExample 1: Let say, we need to reuse the same logic, like passing on the name to every component. Name.js import React from 'react'; // Higher-Order Component (HOC) as a functional component const withName = (OriginalComponent) => { const NewComponent = (props) => { return <OriginalComponent {...props} name="GeeksforGeeks" />; }; return NewComponent; }; export default withName; App.js import React from "react"; import "./App.css"; import withName from './Components/Name'; // Import the HOC // Functional component const App = (props) => { return <h1>{props.name}</h1>; }; // Wrap the App component with the HOC to create the enhanced version const EnhancedComponent = withName(App); // Export the enhanced component export default EnhancedComponent; Output:In this example:HOC Definition: withName is a Higher-Order Component (HOC) that adds a name prop with the value "GeeksforGeeks" to any component passed into it.Original Component: The App component simply renders the name prop inside an <h1> element.Applying the HOC: In App.js, the App component is passed to the withName HOC, creating a new component, EnhancedComponent.Enhanced Component: The EnhancedComponent now has the name prop and will display "GeeksforGeeks" when rendered.Export: The EnhancedComponent is exported and used to display the final output in the browser.Example 2: In this example let's implement some logic. Let's make a counter app. In HighOrder.js, we pass the handleclick and show props for calling the functionality of the component. App.css body { margin: 0; font-family: sans-serif; background: #f0f4f8; display: flex; justify-content: center; align-items: center; height: 100vh; } .container { background: #ffffff; padding: 40px; border-radius: 16px; box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1); text-align: center; } .title { margin-bottom: 20px; font-size: 1.8rem; color: #333; } .count { font-size: 4rem; color: #007bff; margin-bottom: 20px; } .buttons { display: flex; gap: 12px; justify-content: center; } .btn { font-size: 1.5rem; padding: 10px 16px; border: none; border-radius: 8px; background-color: #007bff; color: white; cursor: pointer; transition: 0.3s; } .btn:hover { background-color: #0056b3; } .reset { background-color: #ff4d4f; } .reset:hover { background-color: #d9363e; } withCounter.jsx // src/components/withCounter.jsx import React, { useState } from 'react'; const withCounter = (WrappedComponent) => { return function WithCounter(props) { const [count, setCount] = useState(0); const increment = () => setCount((prev) => prev + 1); const decrement = () => setCount((prev) => prev - 1); const reset = () => setCount(0); return ( <WrappedComponent count={count} increment={increment} decrement={decrement} reset={reset} {...props} /> ); }; }; export default withCounter; Counter.jsx // src/components/Counter.jsx import React from 'react'; import '../App.css'; const Counter = ({ count, increment, decrement, reset }) => { return ( <div className="container"> <h2 className="title">Counter App</h2> <div className="count">{count}</div> <div className="buttons"> <button onClick={increment} className="btn">+</button> <button onClick={decrement} className="btn">-</button> <button onClick={reset} className="btn reset">Reset</button> </div> </div> ); }; export default Counter; App.jsx // src/App.jsx import React from 'react'; import withCounter from './components/withCounter'; import Counter from './components/Counter'; import './App.css'; const EnhancedCounter = withCounter(Counter); const App = () => { return <EnhancedCounter/>; }; export default App; index.js // src/index.js import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<App />); Output:ReactJS Higher-Order ComponentsIn this example:App.jsx: The App component imports and uses the EnhancedCounter, which is the Counter component wrapped by the withCounter HOC to add counter logic.index.js: It renders the App component to the root DOM element using ReactDOM.createRoot.withCounter.jsx: The withCounter HOC takes a component (WrappedComponent) and adds state logic (increment, decrement, and reset) for counting.Counter.jsx: The Counter component displays the current count and provides buttons to increment, decrement, or reset the counter value.State Management: The withCounter HOC uses useState to manage the count and passes the count and its control functions as props to the Counter component.Reason to Use Higher-Order ComponentsCode Reusability: HOCs allow you to reuse logic across multiple components without repeating the same code in each one.Separation of Concerns: They help separate the logic and UI, making components easier to manage and maintain.Enhances Readability: By abstracting shared logic into HOCs, your components remain clean and focused solely on rendering UI.Easy to Maintain: Centralizing shared behavior in a HOC reduces code duplication, making it easier to fix bugs and add new features.Best Practices for Using (HOC)Don’t Overuse HOCs: Use HOCs only when necessary. Too many HOCs can make your code complex and harder to manage.Use for Reusable Logic: HOCs are good for adding common features (like authentication or loading states) across multiple components.Pass All Props: Make sure the HOC passes all the props from the original component to the new one, unless you specifically want to modify or add something.Name Components Clearly: Always give meaningful names to wrapped components, which helps in debugging and readability.ConclusionHigher-Order Components (HOCs) are a powerful tool in React for reusing component logic and enhancing components without changing their original behavior. By wrapping a component with an HOC, you can add extra functionality such as authentication, data fetching, or logging. Comment More infoAdvertise with us Next Article Code Splitting in React S shiv_ka_ansh Follow Improve Article Tags : Web Technologies ReactJS ReactJS-Basics Similar Reads React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon 8 min read React FundamentalsReact IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability.It is developed and maintained by Facebook.The latest version of React is React 19.Uses 8 min read React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.We will discuss the following approaches to setup environment in React.Table of Content 3 min read React JS ReactDOMReactDom is a core react package that provides methods to interact with the Document Object Model or DOM. This package allows developers to access and modify the DOM. Let's see in brief what is the need to have the package. Table of ContentWhat is ReactDOM ?How to use ReactDOM ?Why ReactDOM is used 3 min read React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi 6 min read ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are different from DOM elements as React elements are simple JavaScript objects and are effic 3 min read React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite 5 min read React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc. 5 min read ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the 5 min read Components in ReactReact ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render 4 min read ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.What are Reactjs Functio 5 min read React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el 4 min read ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p 4 min read ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon 2 min read ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he 5 min read React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo 7 min read React HooksReact HooksReactJS Hooks are one of the most powerful features of React, introduced in version 16.8. They allow developers to use state and other React features without writing a class component. Hooks simplify the code, make it more readable, and offer a more functional approach to React development. With hoo 10 min read React useState HookThe useState hook is a function that allows you to add state to a functional component. It is an alternative to the useReducer hook that is preferred when we require the basic update. useState Hooks are used to add the state variables in the components. For using the useState hook we have to import 5 min read ReactJS useEffect HookThe useEffect hook is one of the most commonly used hooks in ReactJS used to handle side effects in functional components. Before hooks, these kinds of tasks were only possible in class components through lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.What is 4 min read Routing in ReactReact RouterReact Router is a library for handling routing and navigation in React JS Applications. It allows you to create dynamic routes, providing a seamless user experience by mapping various URLs to components. It enables navigation in a single-page application (SPA) without refreshing the entire page.This 6 min read React JS Types of RoutersWhen creating a React application, managing navigation between different views or pages is important. React Router is the standard library for routing in React, enabling seamless navigation while maintaining the Single Page Application (SPA) behaviour.What is React Router?React Router is a declarati 10 min read Advanced React ConceptsLazy Loading in React and How to Implement it ?Lazy Loading in React is used to initially load and render limited data on the webpage. It helps to optimize the performance of React applications. The data is only rendered when visited or scrolled it can be images, scripts, etc. Lazy loading helps to load the web page quickly and presents the limi 4 min read ReactJS Higher-Order ComponentsHigher-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 Code Splitting in ReactCode-Splitting is a feature supported by bundlers like Webpack, Rollup, and Browserify which can create multiple bundles that can be dynamically loaded at runtime.As websites grow larger and go deeper into components, it becomes heavier. This is especially the case when libraries from third parties 4 min read React ProjectsCreate ToDo App using ReactJSIn this article, we will create a to-do app to understand the basics of ReactJS. We will be working with class based components in this application and use the React-Bootstrap module to style the components. This to-do list can add new tasks we can also delete the tasks by clicking on them. The logi 3 min read Create a Quiz App using ReactJSIn this article, we will create a quiz application to learn the basics of ReactJS. We will be using class components to create the application with custom and bootstrap styling. The application will start with questions at first and then the score will be displayed at last. Initially, there are only 4 min read Create a Coin Flipping App using ReactJSIn this article, we will build a coin flipping application. In which the user can flip a coin and get a random result from head or tails. We create three components 'App' and 'FlipCoin' and 'Coin'. The app component renders a single FlipCoin component only. FlipCoin component contains all the behind 3 min read How to create a Color-Box App using ReactJS?Basically we want to build an app that shows the number of boxes which has different colors assigned to each of them. Each time the app loads different random colors are assigned. when a user clicks any of the boxes, it changes its color to some different random color that does not equal to its prev 4 min read Dice Rolling App using ReactJSThis article will create a dice-rolling application that rolls two dice and displays a random number between 1 and 6 as we click the button both dice shake and generate a new number that shows on the upper face of the dice (in dotted form as a standard dice). The numbers on the upper face are genera 5 min read Guess the number with ReactIn this article, we will create the guess the number game. In which the computer will select a random number between 1 and 20 and the player will get unlimited chances to guess the number. If the player makes an incorrect guess, the player will be notified whether the guess is is higher or lower tha 3 min read Like