Higher-Order Components

A Function That Wraps a Component

Higher-Order Components

An HOC is a function `Component → Component`. Useful, but largely replaced by hooks for sharing logic.

3 min read Level 2/5 #react#patterns#hocs
What you'll learn
  • Recognize an HOC
  • Use HOCs sparingly — usually hooks are better

A higher-order component is a function that takes a component and returns a new component with extra behavior wrapped around it.

function withLogger(Component) {
  return function Wrapped(props) {
    console.log(Component.name, "rendered with", props);
    return <Component {...props} />;
  };
}

const LoggedButton = withLogger(Button);

Now LoggedButton works like Button but logs on every render.

What HOCs Were Used For

  • Adding context — withRouter, withRedux connect-style HOCs
  • Adding authentication — withAuth(Page)
  • Adding analytics — withTracker(Component)
  • Adding error boundaries — withErrorBoundary(Component)

Almost all of these have a hooks replacement today: useRouter, useSelector, useAuth, etc.

Why Hooks Replaced HOCs

  • No “wrapper hell” in the component tree
  • Easier to compose multiple behaviors — one hook call each
  • Better names — useAuth() reads better than withAuth(MyPage)
  • Better types in TypeScript

When To Still Use HOCs

  • Wrapping a component with error boundaries — these still need to be class components, so HOC is a clean wrapper
  • Library APIs that have to accept any component, no matter what hooks it uses (rare in app code)

For everything else, write a hook.

Up Next

Rendering outside the normal DOM tree — modals, tooltips, popovers.

Portals →