Before we start learning about the Higher-order component (HOC), first we’ll see what Higher-order functions are.
Let’s take a simple code,
- const sum= (number1,number2)=>{
- return number1 + number2;
- }
The above function is simple, it accepts two input numbers and returns the sum of those two numbers.
Now we can take another function,
- const calculator = (operationType) => {
- if (operationType === “sum”) {
- return sum;
- }
- }
The above function is a higher order function, because it accepts an input string as “sum” and returns the sum functions. We can test this by console the result.
- Console.log( calculator(“sum”)(2,5)); // returns 7
Here, calculator is the first level function, which accepts “sum” as a string, which return another function, by passing input values (2, 5) to that function, finally it’ll return 7. So here the calculator function is a higher order function.
The same concept for Higher-order component (HOC).
According to the React documentation (react.org), “A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.”
Simply, a higher-order component is a function that takes a component and returns a new component. Whereas a component transforms props into UI, a higher-order component transforms a component into another component.
- Const EnchancedWrappedComponent = higherOrderComponent(WrappedComponent);
Here, where the higherOrderComponent is HOC Component that adds some additional functionality to the original component which is WrappedComponent and return an EnchancedWrappedComponent.
HOC in simple terms,
- It is a component.
- Which takes two arguments, first is a component and 2nd is a data.
- Then it returns a new component.
- The returned component is an enhanced version of the component that we have passed.
Let’s take two components, LikesCount and CommentsCount
LikesCount.js
- Export default class LikesCount extends component {
- Constructor(props) {
- This.state = {
- Likes: 0
- }
- }
- handleClick = () => {
- this.setState({
- likes: this.state.likes + 1
- })
- }
- Render() {
- Return( < div > {
- this.state.likes
- } < br / > < button onClick = {
- this.handleClick
- } > Like < /button> < /div>)
- }
- }
CommentsCount.js
- Export default class CommentsCount extends component {
- Constructor(props) {
- This.state = {
- comments: 0
- }
- }
- handleClick = () => {
- this.setState({
- comments: this.state.comments + 1
- })
- }
- Render() {
- Return( < div > {
- this.state.comments
- } < br / > < button onClick = {
- this.handleClick
- } > Add Comment < /button> < /div>)
- }
- }

Join the conversation! Your thoughts help the community grow.