This guide outlines how to define higher order components in React with coding examples and points to consider.
React, an open source JavaScript library which is component based, lightweight, flexible, and efficient in building front-end apps in the real-world context was developed in 2011.
In React, there is a higher order component, shortly referred to as HOC which is seemingly the most advanced technique which is used in the reuse of component logic. A higher order component is not part of the React API as is said by the developers but they instead are the model which begins from the compositional nature of the React.
A High-Order Component (HOC) has the work of taking up a function as an advanced arguments and return the same as a function. As clarified that HOC is not one of the feature in React or in any other programming languages but it is a set structured pattern that emerges out from the component nature of the React. Some of the examples of the higher order functions are the .filter, .map, and so on.
ALSO READ: How to get a Javascript project started: JS explainer
What are higher order components?

Higher order components, referred to as HOC are above all a distinctive element which is used in the reuse of the logic in the React components. The members are allowed to use one or more such elements as arguments and then return the same with giving an enhanced new feature to it. Higher order components are similar to higher-order function whose job is to take functions as an argument and produce new function but higher order components are distinct in terms because it is commonly used in the composition of components with a share behavior. HOC combines in a different way from regular state to props pattern.
To note, higher order components do not mutate or modify components but create brand new ones and they are used to compose disintegrated pieces for reuse of logic. It is a pure function, having no side effects which always return a new feature. Some of the examples of real-world higher order components are:
- react-redux Connect(mapStateToProps, mapDispatchToProps) (UserPage)
- material-ui withStyles(styles)(UserPage)
- react-router withRouter(UserPage)
How to Define a Higher-Order Components (HOC) Function
Example 1: Higher-order function which takes up another function as an argument are described in the form of coding as below;
object FunctionThatTakesFunction extends App {
def math(a:Int, b:Int, fun:(Int,Int)=>Int):Int = fun(a,b)
val sum = math(5, 6, (a,b) => a+b)
val diff = math(10, 4, (a,b) => a-b)
println(s”sum is $sum”)
println(s”diff is $diff”)
}
Output:
sum is 11
diff is 6
Example 2: Function that sums an array of numbers:
function calculate(numbers) {
let sum = 0;
for (const number of numbers) {
sum = sum + number;
}
return sum;
}
calculate([1, 2, 4]); // => 7
Output
Sum = 7
Anonymous Functions
Before you start working with the higher-order components, let us have a brief overview of the anonymous functions of HOC. The anonymous functions are one of the elements used on the JavaScript library which is essential in making the code easy to read under understand. An anonymous function is easily assignable to a variable or it can even be passed into the other functions, to name particular, the higher-order functions.
It is to note that the anonymous functions are also commonly referred to as lambdas which are often considered in use when there is to declare a higher order function or in the like cases where the function is used at one time only. The second case is crucial to consider the performance because it has the potential to save the time, cost, and memory as the anonymous functions do not required to be stored in for the later usage.
For instance, a simple anonymous function is said to be like: x -> x + 1
Here, we see that the input of the anonymous function is x, and the output which comes out is x + 1.
The syntax for anonymous functions somewhat differs in all languages, but usually it is written in the form of (input) → (output).
The anonymous functions used in common parlance because they has the ability to prevent the boilerplate code which is associated with the declarations of the named function. Therefore, in case of the simple functions, which do not require to be reused at all across the different places, in such cases, having an anonymous function seems to be more appropriate.
Common Higher-Order Functions
There is certain higher order functions which are having very crucial role in the modern codebases. The common HOCs pave a way to summarize or iterate lists of the data and they also acts as a useful tool in making the codes much cleaner as they can efficiently deal with the common list of operations rather than to have creating multiple helper code for even the basic list of operations. However, to note that for using the common higher order function, the clarity in mind is going to be of immense help. Let us have a brief look over some of the common higher order components:
Filter
The Filter is one essential function which accepts a test function which should return a Boolean value as an argument and return the same with a new array having contained only those elements which are returned true for test function.
Map
The map is another function that turns one higher order function components into another one by addition of a function to each such element. It is a work of user to help describe the replacement of each of the elements.
Reduce
The reduce function of HOCs is a slight different task than the aforesaid ones because it takes up all the components jointly in a group and then adds them simultaneously using the binary values or operations in order to produce a single value.
Points to consider before using HOCs
There are certain points that you must take into consideration before using Higher Order Components. These points are listed as below:
Components should be pure
HOC should be used as such to avoid any side effects and to compose a component only for reuse. There is no need to mutate the component which has been passed as an argument because if the component is replicated the new behavior would also get reflected outside the enhanced component, making the entire component non-reusable. So, you need to use only composition and not mutation.
HOC convention naming
Choose a display name to properly debug the code. For instance, if HOC is the withLoadingIndicator and the input is component then the return gets to have a display name of withLoadingIndicator(Component).
Avoid invoking HOC inside the render method
If you invoke the HOC inside the render, the HOC component also remains invoked or rendered which can result in performance degradation so it is suggested to always invoke HOD from outside component.
Copying static methods
It is very vital to declare static methods only in the class because binding the component where it is defined would lead component non access to the static method.
Advantages of using HOCs
Overall, if we see the advantages of using HOCs, there are hosts of them but to name some:
- HOCs when are properly and efficiently used becomes easy to handle
- HOCs helps in getting rid of the mutating the same logic in the each created component.
- Using the HOCs makes the code more readable and understandable and with its naming conventions, debugging of the code becomes handy.
The post How to define higher order components in React appeared first on HOW TO DO EVERYTHING.