The need for HOCs (Higher Order Components) in React

Image for post
Image for post

This week I found myself in need of a way to pass data and functions as props to a component. Due to the constraints of the library I was using, I couldn’t do this in the following conventional manner:

In order to pass awesomeName to a component in the library I was using, I would need to use a pattern in React called High Order Components (HOCs).

High Order Components (HOC)

A HOC is a React Component that wraps another React Component

Not so scary and extremely useful for what I needed to do.

I’m only going to show how I used HOCs to pass props to a component but you should check out this article by franleplant for a great in depth look at HOCs.

Here’s how we create our HOC:

Here’s how we could use it:

This example is arbitrary, but if you ever find yourself in a situation where you need to pass props to a Component and you can’t do it in the traditional manner, the above pattern should help.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store