DEV Community

loading...

Higher-Order Components in React

Jay Cruz
Hey there! I'm Jay. I love to learn and am super passionate about my field, Software Engineering.
Originally published at jay-cruz.Medium on ・3 min read

Image of keyboard
Photo by Karim MANJRA on Unsplash

There are several patterns for implementing reusability with react components. One such pattern that’s considered a bit more of an advanced technique is the higher-order component pattern. In this blog, I’ll refer to them as HOCs.

What’s a HOC?

Before hooks and render props, the HOC pattern was more commonly used than they are now but it’s still a useful technique to have in your toolbox as a React developer. So what are Hocs? For a basic definition of HOCs, the React docs state, “a higher-order component is a function that takes a component and returns a new component” — reactjs.org . The HOC technique comes from the preferred way to utilize code reuse in React which is composition over inheritance.

An example of when the HOC technique can be useful to you is if you have several components with similar logic to each other. Say you have a comment form that is hidden until the user clicks on the show button and a like button that also changes its state when the user clicks. For this example, we’ll have a CommentForm and LikeButton component.

Here we have duplicated methods for our toggle functionality, breaking the rule of Don't repeat yourself (DRY). The HOC technique could be a handy solution to this situation. If we instead make a component that contains this repeated logic, takes in each of our components as an argument, and returns a new one we could solve our problem.

Then all we need to do is import our HOC into each of our components so they can be passed in as the component to be wrapped by our withToggler giving them access to the toggle logic.

Now our toggle logic is contained within one component and it can be easily shared across multiple other components. This gives our application much more flexibility. And since HOCs are also pure functions we don’t have to worry about mutating the passed-in component because we’re returning a brand new one!

Summary

If you’ve used functions like connect in Redux or withRouter from the React Router library then you’ve already been working with higher-order components even if you didn’t realize it. The concept of higher-order functions in which HOCs are inspired by might also sound familiar to you. Although everything we can do with HOCs can be done using the render props technique or react hooks these days, they can still be a good pattern to know if you’re working with legacy code or just want to become a more versatile React developer.

Resources:

Originally published at https://coderjay06.github.io on May 31, 2021.

Discussion (0)