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
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
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 contextreturn !!localStorage.getItem('authToken');};function withAuth(WrappedComponent) {return function AuthenticatedComponent(props) {if (!isAuthenticated()) {// User is NOT authenticated, redirect to login pagereturn <Navigate to="/login" replace />;}// User is authenticated, render the wrapped componentreturn <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 HOCexport default withAuth(Dashboard);
HOC can be used for many use cases:
- Code reuse, logic and bootstrap abstraction (e.g., fetching data, permissions, theming).
- Render hijacking (e.g., conditional rendering or layout changes).
- State abstraction and manipulation(e.g., handling form logic).
- Props manipulation(e.g., injecting additional props or filtering them).
Some of the real-world examples of HOCs in react eco-system:
- connect() from react-redux
- withRouter() from React Router v5
- withTranslation() from react-i18next
- withApollo() from Apollo client
- withFormik from Formik library
- withTheme from styled components