FrontendDeveloper.in

React question detail

What are Higher-Order Components?

A higher-order component (HOC) is a function that takes a component and returns a new enhanced component with additional props, behavior, or data. It’s a design pattern based on React’s compositional nature, allowing you to reuse logic across multiple components without modifying their internals.

We consider HOCs pure components because they don’t mutate or copy behavior from the original component—they simply wrap it, enhance it, and pass through the necessary props. The wrapped component remains decoupled and reusable.

const EnhancedComponent = higherOrderComponent(WrappedComponent);

Let's take an example of a withAuth higher-order component (HOC) in React. This HOC will check if a user is authenticated and either render the wrapped component if authenticated or redirect (or show a message) if not.

withAuth HOC Example:

import React from 'react';
import { Navigate } from 'react-router-dom'; // For redirection (assuming React Router v6)

const isAuthenticated = () => {
// e.g., check for a valid token in localStorage or context
return !!localStorage.getItem('authToken');
};

function withAuth(WrappedComponent) {
return function AuthenticatedComponent(props) {
if (!isAuthenticated()) {
// User is NOT authenticated, redirect to login page
return <Navigate to="/login" replace />;
}

// User is authenticated, render the wrapped component
return <WrappedComponent {...props} />;
};
}

export default withAuth;

Usage

import React from 'react';
import withAuth from './withAuth';

function Dashboard() {
return <h1>Welcome to the Dashboard!</h1>;
}

// Wrap Dashboard with withAuth HOC
export default withAuth(Dashboard);

HOC can be used for many use cases:

  1. Code reuse, logic and bootstrap abstraction (e.g., fetching data, permissions, theming).
  2. Render hijacking (e.g., conditional rendering or layout changes).
  3. State abstraction and manipulation(e.g., handling form logic).
  4. Props manipulation(e.g., injecting additional props or filtering them).

Some of the real-world examples of HOCs in react eco-system:

  1. connect() from react-redux
  2. withRouter() from React Router v5
  3. withTranslation() from react-i18next
  4. withApollo() from Apollo client
  5. withFormik from Formik library
  6. withTheme from styled components
Back to all React questions
Get LinkedIn Premium at Rs 399