React: High Order Components

High Order Components (HOCs) in React are functions that, given a component, enhance it with some extra behaviors, returning a new component.

Usage

A quick example would look like the sample below:

An example for using a HOC would be if you want the same attribute to appear on multiple components such as className.  You could write a HOC such as the one below:

Note the "with" prefix on the name of the HOC.  It is common practice to prefix HOCs that provide some information to the components they enhance using this pattern.

Recompose Library

The Recompose library provides many useful HOCs as small utilities that we can use to wrap our components, moving away from some of their logic.

Check out some of these useful HOCs:

flattenProp()

Sometimes the objects we work with are structurally complex.  You might want to flatten the structure of incoming objects to make them easier to work with in your component.

renameProp()

The renameProp() HOC allows for you to rename a passed prop for use in the component.

You can also combine HOCs to constructed an enhanced component for you application

Performance

Remember to use HOCs with caution.  While they make code much easier to read, the trade off for using HOCs is in performance.  Wrapping a component into a higher order one adds a new render function, a new life cycle method call, and memory allocation.