CodePark/ questions / Component patterns
START PRACTICINGPRACTICE
Frontend question · React › Component patterns

Compare higher-order components, render props and custom hooks for sharing logic.

Custom hooks are the modern default for sharing logic. Higher-order components and render props still work, but they have more downsides.

Higher-order component (HOC). A function that takes a component and returns a new one with extra props, like withAuth(Page). It works, but stacking several HOCs causes problems:

  • It is unclear where a prop came from.
  • Props from different HOCs can collide.
  • The component tree gets deep. This is called wrapper hell.

Render props. You pass a function that the component calls to render, like <Mouse render={pos => <Cursor pos={pos} />} />. The data flow is explicit. But nesting several of them leads to deeply indented callbacks.

Custom hooks. const pos = useMouse() shares stateful logic without adding components to the tree. Values are named explicitly, and several hooks combine easily.

HOCs and render props are still useful when you need to wrap the rendering itself, for example an error boundary. They also fit when a library's API is built that way.

  • A HOC is a function that takes a component and returns an enhanced one. It can cause prop collisions and wrapper hell.
  • Render props are explicit, but nesting them creates callback pyramids.
  • Custom hooks share logic without adding extra nodes to the tree.
  • Hooks are the default way to reuse logic today.
  • HOCs and render props still fit when you need to wrap rendering.