back home

Higher Order Components

[React Design Patterns]

A Higher Order Component (HOC) is a [decorator] component which accepts other components and injects/decorates them with some additional properties.A HOC doesn’t modify the input component, nor does it use inheritance to copy its behavior. Rather, a HOC composes the original component by wrapping it in a container component. A HOC is a pure function with zero side-effects. The biggest downside of HOCs is shadowing of props. If we use multiple HOCs on one component - for instance some from different libraries, the props injected might collide in terms of variable name. This could cause unpredictable behavior and thus should be used carefully. Additionally, HOCs make it a bit harder to understand where certain props of the component came from.

Example of a HOC

const WithLoading = (component) => ({ isLoading, ...props }) => 
        isLoading ? <Spinner /> : component(props);