Higher-Order Components

Kamal Walia
Nerd For Tech
Published in
2 min readFeb 5, 2020

Hello, I’m back with another article this time on HOC, So without wasting any more time let’s start.

If you’re a CS student, I’m pretty sure that you’ve heard about the term D.R.Y. i.e. Don’t Repeat Yourself. Which basically stated as “Every piece of knowledge must have a single, unambiguous, authoritative representation within a system”.

D.R.Y. is aimed at reducing the repetition of software patterns. When the DRY principle is applied successfully, a modification of any single element of a system does not require a change in other logically unrelated elements.

HOC is a pattern for accomplishing DRY in a React codebase.

For example:- let’s say we want to create few components in react all of these components have some functionality in common let’s say this functionality as hovering i.e. whenever a component gets hovered we show a message to the user. Now we can do this by making the hovering logic repeated in all the components or by using HOC.

Before we start on HOC itself let’s talk about a few programming concepts that’ll make learning about HOC easier.

Callbacks and Higher-order functions

In JavaScript, functions are “first-class objects”. What that means is that just like objects/arrays/strings can be assigned to a variable, passed as an argument to a function, or returned from a function, so too can other functions.

Callback:- A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

Higher-order function:- A higher-order function is a function that takes a function as an argument or returns a function.

For example:-

function add (x, y) {
return x + y
}
function addFive (x, addReference) {
return addReference(x, 10)
}
addFive(10, add) // 20

Here addFive is a higher-order function and addReference is the callback.

Because I’ve just said that. Here’s the same code with the variables re-named to match the concepts they’re demonstrating.

function add (x,y) {
return x + y
}
function higherOrderFunction (x, callback) {
return callback(x, 5)
}
higherOrderFunction(10, add)

Let’s now get back to our main topic HOC:-

A Higher-Order Component is:-

  • Obviously a component
  • Takes in a component as an argument
  • Returns a new component
  • The component it returns can render the original component that was passed in.

For example:-

function higherOrderComponent (Component) { 
return class extends React.Component {
render() {
return <Component />
}
}
}

That’s it, for now, I’ve tried to explain the concept of HOC in very simple terms and just the basics of it. See you in my next post.

--

--

Kamal Walia
Nerd For Tech

👨‍💻 Software Engineer | Tech Enthusiast | Wordsmith 📝