Functions as Child Components and Higher Order Components

I have recently been on a Higher Order Component (HOC) craze. HOCs are a good tool for implementing cross-cutting concerns or common functionalities, such as logging and tracking. For more information on HOCs, check out this recent post by my colleague Mehdi Mollaverdi!

Then I discovered Functions as Child Components (FaCC) and a couple of my brain cells perished. FaCC’s are components that receive a function as their child. For example:

So let’s take a trip through struggle town.

Problem

I need to build many show/hide components.

It is basically a component which toggles between showing and hiding certain content.

Let’s start with building a component that’s immediately usable!

The above code is really straightforward, but when we have n number of ConcreteToggles with common behaviour, it’ll quickly become messy. So let’s make it reusable.

Higher Order Components

Attempt I with HOC

The above approach is passable, however, it makes an assumption about the display order of the components. What happens if a reveal more button needs to be below the content? You know what I mean—I hear my brain cells dying again.

Attempt II with HOC

The functionality we want to abstract is mainly a toggle.

We can create a dumb component that decides how to order the components and decides what to do with onToggle and isActive.

We can then wrap that dumb component with toggle HOC. Voilà!

Functions as Child Components

Attempt I with FaCC

When we use FaCC to solve this problem, we don’t need to create an extra ShowHide component, because the consumer can decide what to do with the given values.

Differences

Higher Order Components Functions as Child Components
Consumers don’t do anything – our HOCs are applied at composition time. Consumers do everything! They have more control over composition. The FaCC doesn’t enforce how it’s used!
HOCs are unaware of React state and props at composition time (unless we use an adapter) FaCC have access to states, props and context when making composition decisions.
Can be optimised using shouldComponentUpdate Typically cannot optimise them using shouldComponentUpdate without hindering your composition ability (because it changes on render)

Conclusion

Aside from knowing the when and what to abstract, there’s the how to abstract common functionalities in components. Really, it’s about choosing the right tool you think is best to solve the problem.

Struggle town is a real place where developers like me live.