Higher Order Components HOC

One of the more common ways to share functionality between components are so-called higher order component. Where the idea is that you have a higher order function that returns a component. Basically, anytime you have a function that takes components as an argument and returns another component, that's a augmented version of the component you passed in, you've just created a higher order component.

The most common higher order of component that you've probably seen is the redux connect function. It takes a component and returns the component enhanced by being connected to the redux data store. There's a lot of other ways you can use higher order components, but the general idea is that you're wrapping an existing component in a different component, and returning that as a new component. For a somewhat contrived example, let's say you have a button component, and you want to log everything that happens on it. The best way to do that is to make a higher order log, or the logger component, that wraps your button and adds new functions. Log events, and in the end it renders our button. If we go put that in code, you'll see that it's not really as difficult as it might first sound. We start with our existing button component, which requires no changes. So, let's make a new higher order click logger component, which is going to take care of logging on click events for pretty much any component that we give it. Function, click logger returns class, and in the render method, wrapped component.

Now that we're rendering our wrapped component and passing in all the prop, we have to add an on click event on the log clicked. To be nice we're also going to call the on click component it was passed into us. For the wrap component, we say on click becomes this on click. Open FJS. Log button. We now created a new component called log button, which uses click logger to enhance the normal button component. We say, log button, remove cat is still rendered, but when we click it, it logs out the clicked event, and the normal remove cat stuff still works. Now the cool thing about higher order components is that once you have this click logger functionality built, you can wrap any component that you can think of in this functionality, without having to change the original component, as long as it supports the on click event. So yeah, that's one way to build shareable functionality that you can reuse in different parts of your app.

Know someone who wants to learn React and its whole ecosystem? Share 👇