What is higher order component in React? Explanation with example

What is higher order component in React? Explanation with example
February 06, 2023

A Higher Order Component (HOC) is a technique in React that enables code reuse.

It is a function that takes an existing component as an argument(input) and returns a new component.

This new component "wraps" the original component and can add extra features, such as props or state, to the wrapped component.

Let's take an example,

function higherOrderComponent(WrappedComponent) {
    return (props) => {
        return <WrappedComponent {...props} />;
    }
}

const Component = (props) => {
    return (<h1>Hello {props.name}!</h1>)
};

const NewComponent = higherOrderComponent(Component);

const element = <NewComponent name="React" />;


Let's understand the code

In the above example, higherOrderComponent takes a Component as an argument and returns a new component. Here higherOrderComponent is reusing the Component.

Higher-order function are used in the following scenarios:

Authentication: It can be used to wrap components and provide the authentication state as a prop. This allows you to abstract away the authentication logic and reuse it across multiple components.

Authorization: HOCs can also be used to implement authorization, i.e. determining whether a user has permission to access a certain resource.

Data Fetching: HOCs can be used to fetch data and pass it down as props to the wrapped component. This allows you to abstract away the data-fetching logic and reuse it across multiple components.

UI Theme: HOCs can be used to implement a UI theme, by wrapping components and passing down theme-related props. This allows you to easily change the theme by swapping the HOC.

Code Splitting: HOCs can be used to implement code splitting, by wrapping components and loading the wrapped component lazily. This allows you to optimize the performance of your application by only loading the code that's needed.

Are you looking for a new Job? Get this Front-End Developer Interview Kit to start preparation today to get your Dream Job.



Resources for You

ChatGPT Guide For Software Developers

Learn to use ChatGPT to stay ahead of competition

Front-End Developer Interview Kit

Today, Start preparing to get your dream job!

JavaScript Developer Kit

Start your JavaScript journey today!

Are you looking for Front-end Developer Job?

Get Front-end Interview Kit Now, And Be Prepared to Get Your Dream Job

Get Front-end Interview Kit

Newsletter for Developers!

Join our newsletter to get important Web Development and Technology Updates