Understanding higher-order components

  • Why use HOC: Promote reuse of logic across React components.
  • How to use HOC: The core structure of a HOC is a function that takes a component and returns a new component.
  • HOC are pure functions with no side-effects because the component passed in, is wrapped in a new component.
  • The HOC looks like this: – – State now has a property to inject data from the API fetch into the wrapped component via the prop.
  • React Redux connect has a different function signature of a function returning a function which accepts one argument (ie, ‘component’) to create a HOC.

Understand why and how to use higher-order components with React JS

In this post I will discuss the why and how to use higher-order components ( ) with ReactJS.

Why use HOC: Promote reuse of logic across React components.

Components are the typical element for reuse in React but sometimes features don’t fit into this standard. There might be similar methods used to fetch data but the display is different. An example of this is shown later.

How to use HOC: The core structure of a HOC is a function that takes a component and returns a new component. HOC are pure functions with no side-effects because the component passed in, is wrapped in a new component. Typically data is injected as a prop and additional props are appended to the component.

This is a general compositional pattern and not part of React as such.

I would recommend first building components in the normal React way. When the application is working as expected, review your components to identify shared behaviours. Build the behaviour in a generic enough fashion to work for all existing components. Following this will improve your experience in identifing HOCs even before completing components, but I would hold back and treat it as a refactoring step when deciding to build a new HOC.

Firstly, here’s the working components which have similar data fetching behaviour:

Understanding higher-order components