React Higher Order Component Example

You’re reading this because you heard React core is moving away from Mixins.

Why is this happening?

Most prominently from facebook employee and react contributor Sebastion

To be clear, mixins is an escape hatch to work around reusability limitations in the system. It’s not idiomatic React.
Idiomatic React reusable code should primarily be implemented in terms of composition and not inheritance.

Mixins are essentially inheritance. They add a functions and callbacks to your components, and allows for complete flexibility with sharing code around an application.

The problem is that too much flexibility(mixins provide uninhibited flexibility) creates a higher probability of an engineer using a bad pattern instead of a good one when they have the choice. You, your teammates, your future self will eventually have to maintain code they chose to write.

How do we prevent this?

Enter Higher Order Components (HOC)


Logistically, they are functions that take a component and return a component. Most commonly they append extra props onto the returned component.

This example:

  • takes a RenderedComponent as its only parameter.
  • It renders the the param component.
  • Appends the rating for that item depending on its type.

TL;DR: We have a function that returns a component.


How do we use it?

  • Import the HOC.
  • Write your component.
  • Export your component wrapped in your HOC.

It essentially creates a new component with the new data attributes that you want.

Three Simple rules to HOC:

  • its just a function
  • The function takes a component
  • The function returns a component

:boom: