0Pricing
React Academy · Lesson

Higher-Order Components (HOCs) Explained

Wrap components to inject props, guard routes, or add logging via HOC factories.

Higher-Order Components (HOCs) Explained is a free React Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Welcome

In this lesson you will understand higher-order components (HOCs), how to write them, common use cases, and their trade-offs compared to hooks.

What Is a HOC?

A Higher-Order Component is a function that takes a component as input and returns a new, enhanced component. The HOC adds behaviour (like props, auth checks, or logging) without modifying the original component.
// HOC signature
function withEnhancement(WrappedComponent) {
  return function Enhanced(props) {
    // add behaviour here
    return <WrappedComponent {...props} extraProp="value" />;
  };
}

Auth Guard HOC

A common HOC redirects unauthenticated users to a login page. The original component never needs to know about auth logic.
function withAuth(Component) {
  return function AuthGuard(props) {
    const isLoggedIn = useAuth();
    if (!isLoggedIn) return <Navigate to="/login" />;
    return <Component {...props} />;
  };
}

const ProtectedPage = withAuth(DashboardPage);

Logging HOC

A HOC can log every render with the component's name and props for debugging. Wrap any component with withLogger to add tracing.
function withLogger(Component) {
  return function Logged(props) {
    console.log('[render]', Component.displayName, props);
    return <Component {...props} />;
  };
}

Passing Props Through

Always spread all received props onto the wrapped component with `{...props}`. Failing to do this breaks the original component's API.
return function HOC(props) {
  return <WrappedComponent {...props} injectedProp={value} />;
};

Setting displayName

HOC-returned components lose their name in React DevTools. Set a meaningful displayName so you can identify them in the component tree.
function withAuth(Component) {
  function AuthGuard(props) { /* ... */ }
  AuthGuard.displayName = 'withAuth(' + (Component.displayName || Component.name) + ')';
  return AuthGuard;
}

Forwarding Refs

HOCs block refs by default. Use `React.forwardRef` inside the HOC to pass refs through to the wrapped component.
function withStyle(Component) {
  return React.forwardRef(function (props, ref) {
    return <Component ref={ref} {...props} className="styled" />;
  });
}

HOC vs Render Props vs Hooks

HOCs inject props and can protect routes. Render props pass dynamic UI. Custom hooks extract logic. In modern React, hooks are preferred because they avoid wrapper hell and are easier to compose. HOCs are useful for class components or third-party integrations.

Wrapper Hell

Applying many HOCs creates deep nesting in the component tree: `withTheme(withAuth(withLogger(MyPage)))`. DevTools shows many anonymous wrapper layers. Hooks avoid this completely.

HOCs in the Wild

Redux's `connect()`, React Router v5's `withRouter()`, and MobX's `observer()` are all HOCs. Understanding HOCs helps you work with these older library APIs.

Quick Check

What must a higher-order component always do with the props it receives?

Recap

HOCs are functions that take a component and return an enhanced one. They inject props, guard routes, and add logging. Always spread props, set displayName, and forward refs. Prefer hooks in modern React.

Up Next

Next lesson: **HOC vs Render Props vs Custom Hooks** — you will compare the three code-sharing strategies on readability, testing, and composition.

Frequently asked questions

Is the “Higher-Order Components (HOCs) Explained” lesson free?

Yes — the full text of “Higher-Order Components (HOCs) Explained” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.

What will I learn in “Higher-Order Components (HOCs) Explained”?

Wrap components to inject props, guard routes, or add logging via HOC factories. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start React Academy?

No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Higher-Order Components (HOCs) Explained” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this React Academy lesson?

Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Render Props Pattern
  2. Higher-Order Components (HOCs) Explained
  3. HOC vs Render Props vs Custom Hooks
  4. Refactoring a HOC to a Custom Hook
← Back to React Academy