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.js the compose function comes up a lot, here’s a nice way to clean up the syntax and make adding HOCs to your code easier.

Using compose()

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

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

Using proposed pipeline operators

// With pipeline operator
export 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 need to reverse the order of your HOCs to keep the call stack equivalent.

With pipeline operators the code is simply 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.

export 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.

Read next:

Fujifilm X lens 35mm equivalence

How to safely get deeply nested properties in ESNext