Higher-Order Components — React

A HOC (Higher-Order Component) is a function that takes a component and returns a new component that wraps it. A HOC's name starts with with, its parameter is…

Ten pages all need the same frame around them, or a check that the visitor is logged in first. Do you write that frame and that check again in ten components? There's a tidier way: make a function that takes a component and returns a wrapped version of it.

A function that takes a component and returns a new component is called a Higher-Order Component (HOC). What a HOC returns is a new component that wraps the original with something extra: a frame, a check, or extra props. The original component isn't changed at all. It works like the laminating machine at a print shop: you hand over any document, and you get back a laminated copy. Your original stays plain, and the same machine works for other documents too. In React, the laminating machine is the HOC, your original document is the original component, and the laminated copy is the new component.

A function that takes a component

Start with an ordinary component that greets through a name prop:

function Greeting({ name }) {
  return <p id="greeting">Hello, {name}!</p>
}

The HOC, withWrapper, puts that greeting inside a frame:

function withWrapper(Component) {
  return function WithWrapper(props) {
    return (
      <div id="wrapper">
        <Component {...props} />
      </div>
    )
  }
}

// called once, outside every component
const GreetingWithWrapper = withWrapper(Greeting)

function App() {
  return <GreetingWithWrapper name="Budi" />
}

Greeting itself doesn't change. <Greeting name="Budi" /> still shows just the <p>, with no div. Only the new component, GreetingWithWrapper, is wrapped.

How the props travel, from App to the screen

This table follows the name prop from App to Greeting:

Step Component Props it receives What it renders
1 App (none) <GreetingWithWrapper name="Budi" />
2 WithWrapper { name: "Budi" } <div id="wrapper"> holding <Greeting {...props} />
3 Greeting { name: "Budi" } <p id="greeting">Hello, Budi!</p>

The final result on the page:

<div id="wrapper">
  <p id="greeting">Hello, Budi!</p>
</div>

The component tree (the way components sit inside each other) now has two layers: WithWrapper outside, Greeting inside. If step 2 writes <Component /> without {...props}, Greeting receives {}, and the greeting becomes Hello, !.

A HOC that adds logic

A HOC can do more than add a frame. withLoading decides whether the original component may render at all:

function withLoading(Component) {
  return function WithLoading({ isLoading, ...props }) {
    if (isLoading) {
      return <p>Loading...</p>
    }
    return <Component {...props} />
  }
}

const EnhancedGreeting = withLoading(withWrapper(Greeting))

// <EnhancedGreeting name="Budi" isLoading={true} />   shows: Loading...
// <EnhancedGreeting name="Budi" isLoading={false} />  shows: Hello, Budi! inside div#wrapper

Rules for writing a HOC

Why it's rarely used now: custom hooks

HOCs were popular before hooks existed (before React 16.8, in 2019). Today, when what you want to reuse is logic (state, effects), the way to do it is a custom hook: a function starting with use that you call right inside the component. You'll build one two lessons from now. Compare the two shapes:

// HOC: the user data is injected as a prop, through one extra layer of component
const ProfileWithUser = withUser(Profile)

// Custom hook: called right in the component, no extra layer
function Profile() {
  const user = useUser()
  return <p>Hello, {user.name}!</p>
}

⚠️ Props lost on the way, and state that keeps resetting

TL;DR: A HOC (Higher-Order Component) is a function that takes a component and returns a new component that wraps it. A HOC's name starts with with, its parameter is usually named Component, and the new component shows <Component {...props} /> so every prop still reaches the original component. The original component doesn't change. Call the HOC once outside every component: const GreetingWithWrapper = withWrapper(Greeting). A HOC can add a frame (withWrapper) or logic (withLoading), and HOCs stack. Each HOC adds one wrapper layer. In new code, reused logic is usually written as a custom hook (a function starting with use, called inside the component); you'll still meet HOCs in older code and libraries.

⚡ A function that takes a component

Write:

function withWrapper(Component) {
  return function WithWrapper(props) {
    return (
      <div id="wrapper">
        <Component {...props} />
      </div>
    )
  }
}

// called once, outside every component
const GreetingWithWrapper = withWrapper(Greeting)
Guess first: the withWrapper above is a HOC (Higher-Order Component). A HOC is a function that takes what, and returns what?

It takes a component, then returns a new component that wraps it. Here, withWrapper takes Greeting (a greeting component) and returns GreetingWithWrapper, which puts Greeting inside <div id="wrapper">.

Meaning: A HOC's name starts with with, and its parameter is usually called Component. Call the HOC once, outside any component, and keep the result in a constant. If you call a HOC inside a component, the component it returns is made again on every render, and the state inside it is lost.

⚡ Pass every prop on

Write:

<Component {...props} />

Meaning: {...props} passes every prop that WithWrapper receives on to the original component, Greeting. Greeting shows Hello, {name}!. Without {...props}, Greeting receives {}, so the greeting reads Hello, !.

⚡ Custom hooks are more common now

Meaning: HOCs were popular before hooks existed. When what you want to reuse is logic (state, effects), the way to do it is a custom hook: a function starting with use that you call right inside the component, with no extra wrapper layer.

What you will learn