Skip to content
A photo of many interconnecting pipes against a backdrop of a brick wall. The photo is heavily tinted blue and cyan.

Use new pipeline operator with React HOCs

There are many ways to use the new proposed pipeline operator in JavaScript, especially when combined with the partial application syntax proposal.

In React the compose function comes up often, here’s a nice way to clean up the syntax and make adding HOCs to your code easier.

Using compose()

export default compose(
  withState('menuSectionIndex', 'setMenuSectionIndex', 0),
  connect(state => pick(['menuSections', 'products']),
)(MenuSection);

There are some downsides to using the compose function. The flow of code is from bottom to top, and refactoring to simply export a component without HOCs is not as trivial as with pipelines.

Using proposed pipeline operators

// Using pipeline operators
export default MenuSection
  |> connect((state) => pick(['menuSections', 'products']))
  |> withState('menuSectionIndex', 'setMenuSectionIndex', 0);

Because the pipeline operator has left to right function composition and compose has right to left function composition, you'll need to reverse the order of your HOCs to keep the call stack equivalent.

With pipeline operators the code can be read from top to bottom. Refactoring is now trivial, you only need to delete the lines after the export to get a HOC-less export.

Composing a HOC with pipeline operators

In the case you don’t want to provide a component right away, you must wrap the pipes in a function so they don’t get evaluated immediately.

// Using compose
export const enhance = compose(
  withState('menuSectionIndex', 'setMenuSectionIndex', 0),
  connect(state => pick(['menuSections', 'products']),
)

// Using pipeline operators
export const enhance = Component => Component
  |> connect(state => pick(['menuSections', 'products']))
  |> withState('menuSectionIndex', 'setMenuSectionIndex', 0);

Conclusion

This is just a simple example of using the proposed pipeline operators to help write more understandable code. Combined with functional programming libraries like Ramda the pipeline operator makes writing composed functions a breeze.