React Higher-Order Components
A higher order component function accepts another function as an argument. The map function is the best example to understand this. The main goal of this is to decompose the component logic into simpler and smaller functions that can be reused as you need.
We know that component transforms props into UI, and a higher-order component converts a component another component and allows to add additional data or functionality into this. Hocs are common in third-party libraries. The examples of HOCs are Redux's connect and Relay's createFragmentContainer.
Now, we can understand the working of HOCs from the below example.
In the above example, we have created two functions add() and higherOrder(). Now, we provide the add() function as an argument to the higherOrder() function. For invoking, rename it addReference in the higherOrder() function, and then invoke it.
Here, the function you are passing is called a callback function, and the function where you are passing the callback function is called a higher-order(HOCs) function.
Create a new file with the name HOC.js. In this file, we have made one function HOC. It accepts one argument as a component. Here, that component is App.
Now, include HOC.js file into the App.js file. In this file, we need to call the HOC function.
The App component wrapped inside another React component so that we can modify it. Thus, it becomes the primary application of the Higher-Order Components.
When we execute the above file, it will give the output as below screen.
Higher-Order Component Conventions