Higher-Order Component Pattern in JavaScript Explained
A higher-order component is a function that takes a component and returns an enhanced one. See React 19 examples, the pitfalls and how hooks replace many uses.

A higher-order component, or HOC, is a function that takes a component and returns a new component with added behavior. It is the component-level version of a higher-order function: a function that takes or returns functions. Before hooks, HOCs were the main way to share logic such as authentication checks, data loading and logging across components. This post shows the pattern with React 19 using renderToStaticMarkup, so each output is readable from the code, then covers the naming and prop-forwarding rules, the common bugs, and where hooks and plain composition do the job better.
The shape
A HOC is a function with this signature: component in, component out. The returned component renders the original one, usually with extra props or extra behavior around it.
export function withGreeting(Component, greeting) {
return function WithGreeting(props) {
return (
<div>
<p>{greeting}</p>
<Component {...props} />
</div>
);
};
}
function Profile({ name }) {
return <h1>{name}</h1>;
}
export const GreetedProfile = withGreeting(Profile, "Welcome back");import { renderToStaticMarkup } from "react-dom/server";
import { GreetedProfile } from "./withGreeting.jsx";
console.log(renderToStaticMarkup(<GreetedProfile name="Ada" />));<div><p>Welcome back</p><h1>Ada</h1></div>withGreeting wrapped Profile without editing it. The wrapper passes every prop through with {...props}, which is essential: a HOC that swallows props breaks the component it wraps.
A useful case: guarding a screen
The standard example is authorization. Many screens need the same "must be signed in" check, and a HOC states it once.
export function withAuth(Component) {
return function WithAuth({ user, ...rest }) {
if (!user) return <p>Please sign in</p>;
return <Component user={user} {...rest} />;
};
}
function Settings({ user }) {
return <h1>Settings for {user.name}</h1>;
}
export const ProtectedSettings = withAuth(Settings);import { renderToStaticMarkup } from "react-dom/server";
import { ProtectedSettings } from "./withAuth.jsx";
console.log(renderToStaticMarkup(<ProtectedSettings user={null} />));
console.log(renderToStaticMarkup(<ProtectedSettings user={{ name: "Ada" }} />));<p>Please sign in</p>
<h1>Settings for <!-- -->Ada</h1>The first render shows the fallback and never creates Settings. The second passes the user through. The comment node between for and Ada is how React separates adjacent text values in server output. The guard is written once and can wrap ten screens.
Composing several HOCs
HOCs stack. Each wraps the result of the one inside it, so you can apply several to one component. A small compose helper keeps that readable.
const compose = (...fns) => (x) => fns.reduceRight((acc, fn) => fn(acc), x);
const trace = [];
const withA = (C) => { trace.push("A applied"); return C; };
const withB = (C) => { trace.push("B applied"); return C; };
const enhance = compose(withA, withB);
enhance("Component");
console.log(trace);[ 'B applied', 'A applied' ]compose(withA, withB) applies withB first, then withA, like function composition in mathematics, so withA ends up as the outermost wrapper. At render time the outermost wrapper runs first. Documenting the order matters when two HOCs interact, for example when authentication must run before a data loader.
Rule 1: forward props and refs
A wrapper that drops props breaks the component inside. Spread everything you do not own. React 19 treats ref as a regular prop for function components, so spreading props forwards it too, which removes the forwardRef boilerplate that older HOCs needed. In earlier versions, a HOC had to use React.forwardRef or the ref would point at the wrapper and not the wrapped component.
Rule 2: copy static properties
Components sometimes carry static properties such as propTypes, a displayName or custom fields used by a router. A HOC returns a new function, so these do not carry over. Libraries such as hoist-non-react-statics copy them, and if you only need the display name for debugging, set it explicitly.
export function withLogger(Component) {
function WithLogger(props) {
return <Component {...props} />;
}
const name = Component.displayName || Component.name || "Component";
WithLogger.displayName = `withLogger(${name})`;
return WithLogger;
}
function Header() {
return <header>Hi</header>;
}
console.log(withLogger(Header).displayName);withLogger(Header)Without a descriptive name, React DevTools shows a tree of anonymous wrappers, and error stack traces are harder to read.
Pitfall: creating a HOC result during render
Calling the HOC inside a component creates a new component type on every render. React sees a different type each time, so it unmounts and remounts the whole subtree, throwing away state.
import { useState } from "react";
function Page() {
const [count, setCount] = useState(0);
// wrong: a new component type is created on every render
const Guarded = withAuth(Settings);
return <Guarded user={{ name: "Ada" }} />;
}Apply the HOC once, at module level, as the earlier examples do. This is the most common HOC bug, and the symptoms are lost input focus and state that resets on every update.
Pitfall: props that collide
A HOC that injects a prop can overwrite one the caller passed, or be overwritten by it.
function withTheme(Component) {
return function WithTheme(props) {
return <Component theme="dark" {...props} />;
};
}
function Badge({ theme }) {
return <span className={theme}>badge</span>;
}
const Themed = withTheme(Badge);import { renderToStaticMarkup } from "react-dom/server";
console.log(renderToStaticMarkup(<Themed />));
console.log(renderToStaticMarkup(<Themed theme="light" />));<span class="dark">badge</span>
<span class="light">badge</span>Because {...props} comes after theme="dark", the caller's value wins, which makes "dark" a default. Reverse the order and the HOC always wins. Either is defensible, and the choice should be deliberate and documented. Namespacing injected props, such as themeContext, reduces accidents.
How hooks changed the picture
Most HOCs written to share stateful logic are better as hooks. A hook has no wrapper component, no prop collisions and no nesting.
import { createContext, useContext } from "react";
export const UserContext = createContext(null);
export function useUser() {
return useContext(UserContext);
}
export function Settings() {
const user = useUser();
if (!user) return <p>Please sign in</p>;
return <h1>Settings for {user.name}</h1>;
}import { renderToStaticMarkup } from "react-dom/server";
import { UserContext, Settings } from "./useUser.jsx";
console.log(
renderToStaticMarkup(
<UserContext value={{ name: "Ada" }}>
<Settings />
</UserContext>,
),
);<h1>Settings for <!-- -->Ada</h1>React 19 lets you render a context directly as a provider with <UserContext value={...}>, so .Provider is not needed. The guard now lives in a hook that any component can call.
Where HOCs still make sense
HOCs remain useful when you need to wrap a component without editing it, such as in library code that adds behavior to a component you do not own. They also fit when you must change what is rendered around the component, such as an error boundary, which must be a class component in React and can be applied through a HOC.
import { Component } from "react";
class Boundary extends Component {
state = { failed: false };
static getDerivedStateFromError() {
return { failed: true };
}
render() {
return this.state.failed ? <p>Something went wrong</p> : this.props.children;
}
}
export const withErrorBoundary = (Wrapped) =>
function WithErrorBoundary(props) {
return (
<Boundary>
<Wrapped {...props} />
</Boundary>
);
};Libraries such as Redux's connect and React Router's older withRouter were HOCs, and you will meet them in older code. Recognizing the shape lets you read it, and migrating usually means replacing the HOC with the equivalent hook.
Testing
Test the wrapper's behavior, then the wrapped component separately. For the guard, check both branches.
import assert from "node:assert/strict";
import { test } from "node:test";
import { renderToStaticMarkup } from "react-dom/server";
import { ProtectedSettings } from "./withAuth.jsx";
test("the guard hides the screen when there is no user", () => {
const html = renderToStaticMarkup(<ProtectedSettings user={null} />);
assert.equal(html, "<p>Please sign in</p>");
});✔ the guard hides the screen when there is no user (1.8ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0Reading and migrating HOCs in existing code
HOCs are easy to spot in older code: a call such as export default connect(mapState)(withRouter(Page)) wraps a component in layers, and each layer adds props the component reads without declaring where they came from. That is the main readability cost. A reader of Page sees props.history and props.user and has to find which wrapper supplies each one.
To migrate a HOC to a hook, identify what it injects, put the same logic in a custom hook that returns those values, and call the hook inside the component. Replace props.user with const user = useUser(). Do the migration one HOC at a time, from the innermost outward, and run the tests after each. Keep the old HOC as a thin adapter around the hook until every consumer has moved, so the change can land in small steps.
Choosing between HOC, render prop and hook
All three share logic, with different trade-offs. A hook is simplest and works in function components. A render prop gives the caller control over the markup where the logic's result appears. A HOC wraps a component from outside, which is the only option when you cannot edit the component, as with third-party code or when applying the same wrapper to many components at once. If you are writing new code and own the component, start with a hook, and reach for the others when a specific constraint asks for them.
Debugging a stack of HOCs
When three or four wrappers surround a component, a bug can hide in any layer. Open React DevTools and read the component tree from the outside in: each wrapper appears with the displayName you set, and its props show what it received and what it passed on. If a prop is missing at the inner component, the wrapper just above it dropped or renamed it. Temporarily replacing one HOC with a pass-through version narrows the search quickly.


