Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 132 ยท Advanced Patterns

Render Props, Higher-Order Components and Hooks

Understand render props and higher-order components in React, see why hooks replaced most of them, and learn where render props still shine, plus the HOC pitfalls with refs, statics and remounts.

How do you share logic between components? Today the answer is almost always "write a custom hook". But for years React had no hooks, and the community invented two patterns to do the same job: render props and higher-order components (HOCs). You will still meet both in older codebases, in libraries such as Formik, React Router's older APIs and Apollo, and in a few places where they are genuinely the better tool.

This lesson explains both patterns by building them, shows the same logic rewritten as a hook, lists the traps that made people stop using HOCs, and ends with a short guide to what to pick. Knowing the history makes unfamiliar code readable, and it sharpens your sense of what hooks actually solved.

The starting problem

Suppose three different screens each need a small piece of stateful logic: "is this panel open, and how do I toggle it?" The state and the toggle function are identical every time; only the markup differs. Copy and paste works for a day. You want to write the logic once and let each screen decide how it looks.

Pattern 1: render props

A render prop is a prop whose value is a function that returns JSX. The component that owns the logic calls the function with its state and renders whatever comes back. The prop is often called render, or simply children, so it reads like nested JSX.

A Toggle component with a render prop

Toggle knows nothing about buttons or checkboxes; the two callers each build their own UI from the same state. On mount the console prints Toggle renders, isOn = false for the lamp and isOn = true for the notifications toggle. Press the lamp button and exactly one more line, Toggle renders, isOn = true, appears: the other toggle is untouched, because each <Toggle> owns separate state (see State with useState).

What happens on each render? Toggle runs, reads its state, and calls the function it was given, passing the current values. React then renders the returned elements. The function is called during Toggle's render, so it follows the same rules as any render code: keep it pure, and never call hooks inside it unless the render prop itself is a component.

Render props are explicit. When you read the JSX you can see where isOn comes from, and you can name it however you like. Multiple providers compose by nesting, and the data flow is obvious, which is better than the hidden injection of the HOC pattern below.

Why it fell out of favor

Nesting. Two or three render props in one component create the "callback pyramid" that people compared to callback hell:

JSX
<Mouse>
  {(position) => (
    <Theme>
      {(theme) => (
        <Auth>
          {(user) => <Dashboard position={position} theme={theme} user={user} />}
        </Auth>
      )}
    </Theme>
  )}
</Mouse>

It reads badly, it makes the logic hard to use outside JSX (for example in an event handler), and each render creates new inline functions. Hooks flatten the pyramid into three lines.

The same logic as a hook

A custom hook returns exactly what the render prop passed to its function. There is no wrapper component and no callback.

The Toggle logic as a custom hook

The behavior on screen is the same, and the component tree is shallower: no Toggle in between. A hook shares stateful logic, not state: each call to useToggle creates its own state, just as each <Toggle> did. Chapter Custom Hooks covers writing them in depth.

Pattern 2: higher-order components

A higher-order component is a function that takes a component and returns a new, enhanced component. The name mirrors higher-order functions. You will recognize the shape: connect(...)(Component) in older Redux code, withRouter(Component) in React Router v5, withStyles(...) in older Material UI.

The usual recipe: the HOC returns a wrapper component that adds behavior (state, a subscription, a loading branch) and passes the result to the wrapped component as props.

withLoading, a higher-order component

The console logs display name: withLoading(UserList). Setting displayName is a convention: React DevTools and error messages show it, so you see withLoading(UserList) in the component tree instead of a vague Anonymous or WithLoading repeated everywhere.

Three rules make HOCs behave:

  1. Do not mutate the wrapped component. Return a new one; don't patch the original.
  2. Pass unrelated props through ({...props}), as above, so the wrapper is invisible to callers.
  3. Wrap outside of render. This one is the source of the nastiest HOC bug.

HOC pitfall 1: creating the HOC inside render

withLoading(UserList) returns a new component function each time it is called. React identifies components by function identity (see Reconciliation and Keys in Depth). If you call the HOC inside a component body, every render produces a different component type. React sees a different type at the same position, throws the old subtree away and mounts a new one, resetting all state inside.

HOC created during render loses state (fails on purpose)

Type something into both inputs, then click the button. The "outside" input keeps its text; the "inside" input is emptied, and after the initial NoteField mounted: inside and NoteField mounted: outside the console shows NoteField unmounted: inside followed by NoteField mounted: inside. That is the unmount/mount cycle in action. Broken re-renders with its parent (it is not wrapped in memo), and each of its renders builds a brand-new BorderedInside. The fix is simply to call HOCs at module level, once.

HOC pitfall 2: refs and ref forwarding

Before React 19, ref was special: a ref placed on a wrapped component attached to the wrapper, not the inner component, so every HOC author had to learn forwardRef. In React 19, ref is an ordinary prop for function components. That means an HOC that spreads {...props} forwards the ref automatically:

ref passes through an HOC in React 19

The ref reaches the <input> through two layers of function components. (In React 18 and earlier, this required wrapping both layers in forwardRef, otherwise inputRef.current stayed null and a console warning appeared. Class components still never receive ref as a prop; it points to the class instance.)

HOC pitfall 3: other traps

  • Static methods are lost. The wrapper is a different function, so UserList.someHelper does not exist on withLoading(UserList). Libraries copy statics with hoist-non-react-statics. Hooks do not have this issue at all.
  • Prop name collisions. Two HOCs that both inject a prop called data silently overwrite each other. Nothing in the call site tells you which props were injected, so the wrapped component's props come from "somewhere".
  • Wrapper hell. withA(withB(withC(withD(Page)))) makes the DevTools tree deep and the real component hard to find.
  • Order matters. withAuth(withLoading(X)) and withLoading(withAuth(X)) behave differently, and the difference is invisible in the component's own file.
  • Types are hard. With TypeScript, typing "adds these props and removes those" generically is one of the trickiest things to write.

When each pattern still earns its place

Situation Best tool
Share stateful logic between components Custom hook
Subscribe to something (store, media query, window size) Hook, often with useSyncExternalStore
Let the caller choose how each item or region renders Render prop (renderItem, renderEmpty)
Component must wrap other components with markup, error handling or providers Regular wrapper components with children
Add the same wrapper behavior to many components at definition time (logging, error boundary wrapper, analytics) HOC
Class components that cannot use hooks HOC or render props

Where render props are still the right answer

A hook can share logic, but it can't tell a parent how a child's output should look in the middle of the parent's own rendering. When a component owns the loop or the layout and wants the caller to fill small holes, a render prop is the clearest API. Lists are the classic case: the list owns empty states, keys and spacing; the caller decides what one row looks like.

A List with render props for items and empty state

List is generic: it has no idea what a person is. The caller supplies a getKey, a renderItem and a renderEmpty function, and the component stays reusable for products, messages or anything else. Libraries do the same on a larger scale: virtualized lists call renderItem only for visible rows (see Large Lists and Virtualization), form libraries call a render function with field state, and table libraries call cell renderers.

If the function prop only receives data and returns JSX, ask whether a plain component prop would read better: renderItem={PersonRow} with PersonRow as a real component lets you use hooks inside it. A render-prop function called during another component's render must not use hooks itself; a component can.

Converting old code step by step

When you inherit a HOC or render prop and want to modernize it, this procedure keeps the risk low:

  1. Find what the wrapper really provides: state, effects, subscriptions, injected props.
  2. Move that logic into a custom hook that returns the same values (useWindowWidth() instead of withWindowWidth).
  3. Call the hook in the component that used the HOC; remove the injected props from its parameters.
  4. Delete the wrapper once nothing uses it. Keep the HOC for class components until they are migrated, implemented as a thin shell around the hook.

A bridge for step 4 looks like this (read-only, because it needs a class component):

JSX
// Class components cannot call hooks, so the HOC calls the hook for them.
function withWindowWidth(Wrapped) {
  return function WithWindowWidth(props) {
    const width = useWindowWidth();
    return <Wrapped {...props} windowWidth={width} />;
  };
}

The logic lives in one place (the hook); the HOC becomes a ten-line adapter that you can delete when the last class component is gone.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a render prop?

    The component calls the function with its internal state or data and renders what it returns. The caller decides the markup.
  2. 2. Why did hooks replace most render props?

    A custom hook returns the values directly, so there is no callback pyramid and the logic can be used outside JSX. Render props still work, but they are noisier for sharing logic.
  3. 3. What happens if you call withBorder(NoteField) inside a component body?

    React compares component types by identity. A new function each render means a different type, so the old subtree is unmounted and a new one mounted, resetting state. Create HOC results once at module level.
  4. 4. In React 19, how does a ref reach the inner element through an HOC that spreads {...props}?

    Since ref is a normal prop for function components in React 19, the HOC passes it on with the other props. Before 19 you needed forwardRef.
  5. 5. Which task is a good fit for a render prop today?

    When a component owns the structure (looping, keys, empty states) and the caller fills in small regions, a render prop such as renderItem is a clear API. The other tasks are plain hook work.

Summary

  • Render props and HOCs were the pre-hooks ways to share logic: a function prop that returns JSX, and a function that returns an enhanced component.
  • Custom hooks cover most of those cases with less nesting; they share logic, never state.
  • HOC traps: creating them during render (remounts, lost state), lost statics, prop-name collisions, deep wrapper chains and awkward typing. In React 19 ref passes through HOCs that spread props.
  • Set a displayName on wrapper components so DevTools stays readable.
  • Render props (renderItem, renderEmpty) remain a great fit for generic components that own the structure and let callers fill in the details.
  • To modernize old code, extract the logic into a hook and keep a thin HOC adapter only for classes.

Next: Portals and Overlays