From HOCs and Render Props to Custom Hooks
How do I share logic between components without copy-paste? Custom hooks usually avoid nested wrappers for this; HOCs and render props keep a few specific composition tasks.
Four levels in the React DevTools tree before the first one appears that actually renders something visible: withRouter, below it withLoading, below that withData, and at the very bottom the actual page. Three of these levels contribute nothing to the output. They exist only to pass state and behavior from the outside in.
This tree is no accident but the logical consequence of a decision React carried around for years. Reusing stateful logic in several places without duplicating it is something the framework solved differently in three generations – and the first two solutions pay for it with exactly such levels. If you know the sequence, you also understand why the older patterns are still not worthless.
The same old question#
An example that shows this well: a component needs to know whether the browser is currently online. That takes state, it takes an effect with event listeners, and it takes cleanup. If three components need this, nobody wants to write the same block three times.
The naive solution is copy-paste. It works exactly until the logic changes – then you change it in one place and forget the other two. From that point on, React developers look for a mechanism that keeps the logic in exactly one place.
Historically, the path there looked like this:
graph LR A[Copy-Paste] --> B[Mixins<br/>deprecated] B --> C[HOCs &<br/>Render Props] C --> D[Custom Hooks<br/>React 16.8 / 2019]
Mixins were the first answer in the very early days of createClass, but they were quickly discarded as problematic – unclear origin of properties, name collisions, implicit dependencies. After that came two patterns that dominated for a long time: higher-order components and render props. And since React 16.8 – stable since February 2019 – there are custom hooks. Let’s look at the three relevant answers in order.
Answer 1: Higher-order components#
A higher-order component is basically an old acquaintance from functional programming. Just as a higher-order function takes a function and returns a new function, a HOC takes a component and returns a new, enhanced component. The signature is:
// a function that takes a component and returns a new component
const withSomething = (Component) => EnhancedComponent;
The naming convention is withXxx. Let’s take the classic example withLoading, which encapsulates a loading state:
import { Fragment } from "react";
function withLoading(Wrapped) {
return function WithLoading(props) {
if (props.loading) {
return <Spinner />;
}
return <Wrapped {...props} />;
};
}
The whole thing is applied at module level, not in render:
const UserPageWithLoading = withLoading(UserPage);
That reads cleanly. And it composes: you can stack several HOCs, withRouter(withLoading(withData(Page))). But that is exactly where it has its price.
The fact that application has to happen outside of render seems like a formality – until you violate it once. If you create a HOC directly in render(), a new component identity is created on every pass. React sees a different type, unmounts the entire subtree and rebuilds it – all the state below it is lost. That is one of those bugs you debug live once and then never produce again.
On top of that come two more pitfalls you need to know:
- Static methods of the original component disappear, because the wrapper doesn’t copy them along automatically – you need something like
hoist-non-react-statics. - Refs don’t pass through the wrapper as a normal prop. If you need a ref to the inner component, you have to resort to
React.forwardRef(available since React 16.3).
And the basic rule that holds it all together: composition instead of mutation. A HOC doesn’t mutate the component passed in; it wraps it in a container. As soon as someone starts changing the original component directly, the pattern is broken.
Answer 2: Render props#
The second pattern turns the tables. Instead of wrapping one component in another, you give a component a function that tells it what to render. That is a render prop: “a function prop that a component uses to know what to render”. Often you use children directly as a function for this.
class OnlineStatus extends React.Component {
state = { isOnline: false };
handleOnline = () => this.setState({ isOnline: true });
handleOffline = () => this.setState({ isOnline: false });
componentDidMount() {
window.addEventListener("online", this.handleOnline);
window.addEventListener("offline", this.handleOffline);
}
componentWillUnmount() {
window.removeEventListener("online", this.handleOnline);
window.removeEventListener("offline", this.handleOffline);
}
render() {
return this.props.children(this.state.isOnline);
}
}
It is then called like this:
<OnlineStatus>
{(isOnline) => (
<span>{isOnline ? "Online" : "Offline"}</span>
)}
</OnlineStatus>
That is more flexible than a HOC, because the caller keeps full control over rendering. But here too there is a price: if you create the function inline in the JSX, it is recreated on every render. For a PureComponent or a child component optimized with memo, that is poison – the shallow compare fails because the function reference is new every time, and the optimization comes to nothing. You would have to move the function out into a stable instance method, which eats up the supposed elegance again.
The shared problem: wrapper hell#
Both patterns – HOCs and render props – share logic through the same mechanism: additional levels in the component tree. Every HOC is a wrapper, every render prop another level of nesting. With one or two levels, you don’t notice anything. With five, the React DevTools tree looks like an onion, and that is affectionately called “wrapper hell”.
This tree is exactly the crucial point. Let’s look at it:
graph TD
subgraph HOC["HOC / render props: nested"]
R1[withRouter] --> L1[withLoading]
L1 --> D1[withData]
D1 --> P1[Page]
endEvery intermediate level exists only to pass logic in. It has no domain meaning of its own; it is pure infrastructure in the tree. And because the data is passed through from the outside in, intermediate layers with stale closures arise easily – another debugging classic.
Answer 3: Custom hooks#
Custom hooks solve the problem in a different place. A custom hook is simply a normal JavaScript function whose name starts with use and which may call other hooks. No wrapper, no additional component, no new level in the tree. The logic moves into a function, the component calls it – done.
The same withLoading problem looks like this as a hook: the hook supplies the state and the component itself decides what to render with it:
import { useState, useEffect } from "react";
function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(true);
useEffect(() => {
const handleOnline = () => setIsOnline(true);
const handleOffline = () => setIsOnline(false);
window.addEventListener("online", handleOnline);
window.addEventListener("offline", handleOffline);
return () => {
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", handleOffline);
};
}, []);
return isOnline;
}
And the usage is as unspectacular as it should be:
function StatusBar() {
const isOnline = useOnlineStatus();
return <span>{isOnline ? "Online" : "Offline"}</span>;
}
Compare this with the OnlineStatus render prop above: the same logic, but without the nesting, without the inline function, without the class. The tree stays flat:
graph TD Page2[Page] -.calls.-> H1[useData] Page2 -.calls.-> H2[useLoading] Page2 -.calls.-> H3[useRouter]
The hooks hang off the side of the component – they are function calls, not tree levels. That is the whole trick, and it is a big one.
Two properties of custom hooks are worth spelling out explicitly, because they are often misunderstood:
- Custom hooks share logic, not state. If two components call
useOnlineStatus(), each has its own, independent state. The hook is a recipe, not a shared pot. - Custom hooks re-render with their component. On every re-render, the hook gets fresh props and current state – the “stale closures” that arise so easily in HOC intermediate layers are much less of an issue here.
Rules that apply to custom hooks too#
The use prefix is not cosmetic. It signals to the linter and to readers that this function may itself call hooks – and that the Rules of Hooks apply to it. Concretely, that means:
Only React components and other hooks may call hooks. An ordinary function without use may not contain a useState. The reverse applies just as much: a function that doesn’t call any hooks at all shouldn’t be called use. Otherwise you take away your freedom to call it conditionally or in a loop – which is forbidden for real hooks. So the prefix is a contract in both directions. The whole thing is enforced by eslint-plugin-react-hooks, which I never leave out of a React project.
A trap that is less technical than conceptual is one I see in codebases again and again: the urge to immediately build generic “lifecycle” hooks, such as a useMount that wraps an effect on mount. That is usually a bad trade. A custom hook should represent a concrete, nameable use case – useOnlineStatus, useChatRoom, useFormInput. If the hook’s name already explains what it does in domain terms, it is cut well. If it only renames a React mechanism, you’ve gained nothing, and the abstraction will get in your way later.
When HOCs still make sense today#
After all this, it sounds as if custom hooks had completely replaced the two older patterns. For sharing stateful logic, that is largely true. But there is a handful of tasks for which HOCs are still the right form – namely real cross-cutting concerns that are brought to a component from the outside.
The classic example is context injection: a HOC that makes a value from context available to any component as a prop, without the component itself having to know about the context. You often run into such withXxx wrappers in older libraries, and there they serve a purpose that a hook doesn’t cover cleanly – for example when class components are involved, which can’t call hooks at all. So if you maintain an existing codebase with class components, you’ll keep running into HOCs for a while.
What I no longer recommend, on the other hand, is reaching for HOC toolkits like recompose. In its time, the library was a clever tool for composing functions such as withState or withReducer:
// recompose - historical, deprecated since 2018
import { compose, withState } from "recompose";
const enhance = compose(
withState("count", "setCount", 0)
);
However, the author himself marked recompose as deprecated back in 2018 and explicitly pointed to hooks as its successor. So you only come across the package as historical context in older repositories – it is no good as a current recommendation.
The common thread#
Three answers to one question, and the order tells a clear story. HOCs and render props showed that logic can be shared without copying it – but they solved it through the component tree and paid for it with nesting, lost refs and static methods, defeated memo optimizations and “wrapper hell”. Custom hooks solve the same task with a simple function call and keep the tree flat.
For shared logic, the first choice today is therefore a custom hook with a use prefix that encapsulates a concrete use case. HOCs stay in the toolbox for the cross-cutting cases and for work on existing code with class components. And render props still show up where a component really wants to hand control over rendering back to the caller. But the standard case – the same logic in several components – has had a good, unspectacular answer since 2019. You just have to know why the other two were there before.
Further reading#
- Reusing Logic with Custom Hooks – the current chapter on custom hooks
- Higher-Order Components – the historical HOC documentation
- Render Props – the original render props pattern
- Hooks – Custom Hooks (Legacy) – the historical custom hooks chapter
- Rules of Hooks / Invalid Hook Call Warning – why the
useprefix and the rules matter
Revised and translated from German with the help of AI.