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" />
}
withWrapper(Component)is an ordinary function. Its parameter is a component, usually namedComponentorWrappedComponent. The name starts with a capital letter so it can be written as a JSX tag,<Component />.return function WithWrapper(props) {...}: what comes back is a new component.withWrapperitself shows nothing.withWrapperonly makes a component.<Component {...props} />puts the original component inside the div.{...props}passes on every prop the wrapper received, sonamereachesGreeting.- The HOC's result is stored in
GreetingWithWrapper, and used like any other component:<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
{ isLoading, ...props }takesisLoadingout and gathers the rest (name) inprops. SoisLoadingstops at this layer and doesn't travel down.- When
isLoadingis true,WithLoadingreturns<p>Loading...</p>right away.WithWrapperandGreetingdon't render at all. - HOCs stack.
withLoading(withWrapper(Greeting))makes three layers, and the leftmost HOC becomes the outermost layer.
Rules for writing a HOC
- The name starts with
with:withWrapper,withLoading,withAuth. The name alone tells people the function wraps a component. - Pass the props on:
<Component {...props} />, so the original component still gets everything sent to its wrapper. - Don't change the original component. Return a new component, and leave
Greetingas it is. - Call the HOC once, outside every component, and keep the result in a constant.
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>
}
- Every HOC adds a layer to the component tree. Three stacked HOCs means three wrappers to search through when there's a bug.
- A prop from a HOC appears in the original component, and you can't see there where it came from. With a hook, where the data comes from is written on the line that uses it.
- You'll still meet HOCs in older code and in some libraries:
connect(...)(Component)from older Redux, andwithRouterfrom React Router v5. Thememo(Component)you'll learn later has the same shape too: it takes a component, then returns a new one.
⚠️ Props lost on the way, and state that keeps resetting
- Forgetting
{...props}.<Component />with no props makesGreetingreceive{}, so the greeting isHello, !. - Calling the HOC inside render.
const GreetingWithWrapper = withWrapper(Greeting)insideAppmakes a new component every timeApprenders. To React, the new component is different from the one in the previous render, so React throws away what it showed and builds it again from scratch. Any state inside is lost too. - Typing the whole greeting. In the exercise,
<p id="greeting">Hello, Budi!</p>looks right, but it doesn't use the prop. Build it from the prop:Hello, {name}!. - Stacking too many.
withA(withB(withC(withD(Page))))means four wrapper layers. If all you share is logic, use a custom hook.
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.