Hello! Welcome back to our module on Advanced Component and TypeScript Patterns.
In our last lesson, we built a flexible and expressive component API using the compound component pattern, a modern approach that leverages React Context and Hooks. We saw how it gives developers control over composition, avoiding the "prop explosion" problem.
Today, we're going to take a step back in time to understand the patterns that paved the way for modern solutions like hooks. Our focus will be on Higher-Order Components (HOCs) and Render Props. The goal of this lesson is to explain the historical role of these patterns in the React ecosystem. Understanding them is not just an academic exercise; you will encounter them in older codebases, popular libraries, and interview questions. It also provides crucial context for why custom hooks are the preferred solution today.
A Brief History: The Need for Reusable Logic
Before we dive into the patterns themselves, it's important to understand the problem they were designed to solve.
In the early days of React, before the adoption of ES6 classes, components were created with React.createClass. This API had a feature called mixins, which was the primary way to share code and functionality between components. However, as Dan Abramov famously explained, mixins came with significant drawbacks, such as implicit dependencies and name clashes.
When React moved to ES6 classes, mixins were deprecated, leaving a void. How could developers share non-visual, stateful logic across multiple components? Two dominant patterns emerged to fill this gap: Higher-Order Components and Render Props.
Higher-Order Components (HOCs)
A Higher-Order Component is a function that takes a component as an argument and returns a new, enhanced component. If you've worked with decorator patterns in other languages, the concept will feel familiar. It's a way to wrap a component to give it extra "powers" or props.

How an HOC Works
Let's imagine we want to add a simple logging feature to see when our components mount. We could write an HOC for that.
import React, { ComponentType, useEffect } from 'react';
// The HOC is a function that takes a component...
function withLogging<P extends object>(WrappedComponent: ComponentType<P>) {
// ...and returns a new component.
const ComponentWithLogging = (props: P) => {
useEffect(() => {
console.log(`Component ${WrappedComponent.name} mounted.`);
}, []);
return <WrappedComponent {...props} />;
};
// It's good practice to set a display name for debugging.
ComponentWithLogging.displayName = `WithLogging(${WrappedComponent.name || 'Component'})`;
return ComponentWithLogging;
}
// Usage
const MyComponent = (props: { message: string }) => <div>{props.message}</div>;
const MyComponentWithLogging = withLogging(MyComponent);
// In your app:
// <MyComponentWithLogging message="Hello World" />
// Console will log: "Component MyComponent mounted."
In this example, withLogging is the HOC. It doesn't care what MyComponent does; it just wraps it and adds a side effect. A more common use case is injecting props, like user authentication status or data fetched from an API.
The Problems with HOCs
While powerful, HOCs have several well-known drawbacks, which is why they have fallen out of favor for new development.
Higher-order components vs Render Props
This article from Richard Kotze's blog clearly outlines the historical context and the main issues associated with HOCs.
Please read the section titled 'Higher-order components'. Focus on the list of problems it identifies, such as prop collision, boilerplate, and the 'wrapper hell' phenomenon.
To summarize and expand on the issues, especially in a TypeScript context:
- Prop Naming Collisions: If you compose two HOCs (
withAuth(withTheme(MyComponent))) and both inject a prop nameduser, the innermost HOC's prop will be silently overwritten. There is no static way to detect this. - "Wrapper Hell": In React DevTools, you'll see a deep nesting of components:
<WithAuth><WithTheme><MyComponent /></WithTheme></WithAuth>. This makes debugging the component tree difficult. - TypeScript Complexity: Typing HOCs correctly is notoriously hard. The logic that injects new props is opaque to the type system. This means TypeScript and your editor's IntelliSense struggle to know which props are available on the wrapped component, leading to complex generic types and a poor developer experience.
- Implicit Dependencies: It's not clear from the JSX where the props are coming from. A component might receive an
isAuthenticatedprop, but you have to trace back through the export statement to see which HOC provided it.
Render Props
The Render Prop pattern emerged as a solution to many of the problems posed by HOCs. It flips the inversion of control. Instead of your component being passively wrapped, you actively pass a function to a component that then calls that function to render something.
How Render Props Work
A component with a render prop takes a function as one of its props (often named render or, more commonly today, children). This function returns a React element and becomes a part of the component's rendering logic. The component can call this function with arguments, effectively passing state up to the parent for it to decide what to render.
The following video provides an excellent practical demonstration of the pattern.
Ep2 Render Props Pattern | React Design Patterns Series 💪🏻
This video from JsCafe explains what the Render Prop pattern is, discusses its use cases, and provides a live-coding example.
Please watch from the beginning to 12:21. Pay attention to: The definition of a render prop (00:21 - 01:16). The use cases: making components customizable and themeable (01:16 - 04:06). The coding example, where a component shares its internal state (the input value) with its parent via a render prop (04:06 - 12:21).
Render Props and TypeScript
One of the biggest advantages of Render Props over HOCs is how well they work with TypeScript. The data flow is explicit.
Let's look at an AuthProvider example. Compare this to the conceptual complexity of a withAuth HOC.
// ✅ A component that uses the render prop pattern (via `children`)
interface AuthProviderProps {
children: (auth: { isAuthenticated: boolean; user: User | null }) => React.ReactNode;
}
function AuthProvider({ children }: AuthProviderProps) {
// Imagine this state comes from a hook or context
const authState = { isAuthenticated: true, user: { name: 'Alice' } };
// It calls the children function with the auth state
return <>{children(authState)}</>;
}
// Usage is clean, explicit, and type-safe
function MyPage() {
return (
<AuthProvider>
{({ isAuthenticated, user }) => (
// TypeScript knows the exact shape of these arguments!
isAuthenticated ? <h1>Welcome, {user?.name}</h1> : <p>Please log in.</p>
)}
</AuthProvider>
);
}
Here, the children prop is a function. AuthProvider calls it with the authState. Everything is explicit and statically typed. There's no magic prop injection.

The Modern Verdict: Enter Custom Hooks
While Render Props were a big improvement, both patterns have been largely superseded by custom hooks for sharing stateful logic.
A custom hook is a JavaScript function whose name starts with "use" and that may call other hooks. It lets you extract component logic into reusable functions.
Let's reconsider the problem of providing authentication status.
- HOC:
withAuth(MyComponent) - Render Prop:
<AuthProvider>{({ user }) => ...}</AuthProvider> - Custom Hook:
const { user } = useAuth();
The custom hook approach is more direct, more composable, and doesn't introduce any extra component nesting. It solves the original problem of sharing logic in the most elegant way yet.
The following article gives excellent guidance on when to choose which pattern, and importantly, when to avoid HOCs in modern code.
Render Props and HOC Alternatives
This article by Steve Kinney provides a fantastic summary, framing Render Props as a TypeScript-friendly alternative to HOCs and then positioning custom hooks as the modern standard.
Read the sections 'The HOC Problem', 'Render Props: The TypeScript-Friendly Alternative', and 'When to Use Each Pattern'. This will solidify your understanding of the trade-offs and clarify the modern hierarchy of patterns.
Test your understanding!
Imagine you need to create a component that tracks the user's mouse position and makes the x and y coordinates available to other components.
- Briefly describe how you might implement this using a Render Prop component called
<MouseTracker>. - How would you solve the same problem with a custom hook called
useMousePosition? - Which approach is generally preferred today and why?
Show answer
-
Render Prop (
<MouseTracker>): You would create a<MouseTracker>component that contains the state forxandyand uses auseEffectto add and clean up amousemoveevent listener on thewindow. In its render method, it would callprops.children({ x, y }), passing the current coordinates to the function provided as its child.<MouseTracker> {({ x, y }) => <p>The mouse is at ({x}, {y})</p>} </MouseTracker> -
Custom Hook (
useMousePosition): You would create a functionuseMousePositionthat does the exact same thing internally: it would useuseStateto storexandyanduseEffectto manage the event listener. However, instead of rendering anything, it would simplyreturn { x, y }.const MyComponent = () => { const { x, y } = useMousePosition(); return <p>The mouse is at ({x}, {y})</p>; } -
Preferred Approach: The custom hook is overwhelmingly preferred today. It directly provides the logic and state without adding any component nesting to the tree (avoiding "wrapper hell"). It's simpler to use, easier to type, and more composable—you can use multiple custom hooks in a single component without any friction.
Conclusion
You've now explored the evolution of logic-sharing patterns in React. While HOCs and Render Props are not the first tools you should reach for when writing new code, understanding their design and trade-offs is a hallmark of an experienced React developer.
Key Takeaways:
- Historical Context: HOCs and Render Props were created to solve the problem of code reuse after mixins were deprecated.
- Higher-Order Components (HOCs): Wrap components to add functionality. They suffer from implicit prop injection, prop collisions, wrapper hell, and are difficult to type correctly with TypeScript.
- Render Props: Invert control by passing a function as a prop (
renderorchildren). They are more explicit, type-safe, and avoid prop collisions, but can lead to JSX nesting. - The Modern Solution: Custom Hooks are now the standard for sharing stateful logic, offering a more direct, simple, and composable solution that avoids the drawbacks of both older patterns.
Preview of the Next Lesson:
Our exploration of advanced component patterns continues. While HOCs can wrap components, they can't always transparently pass down every feature. One such feature is a ref. In the next lesson, we will cover React.forwardRef, a crucial utility that allows you to pass refs through a component to a DOM element or class component inside it, enabling the creation of truly reusable and interoperable components.