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.
To share common functionality between components.
Let's discuss one example.
We have one component ParentComponent. ParentComponent have two child component ChildComponent1 and ChildComponent2. ChildComponent2 have one child component ChildComponent21. Now, ChildComponent1 and ChildComponent21 both have common function required. then passing this function from props ParentComponent to last child component is not proper solution. So, We can achive this things by higher order components
We can get more idea by looking below example. you can put this file in /src/components folder and put
In above code, Our HOC component inject count and incrementCount to WrappedComponent. which we passed as withCounter(ChildComponent1); HOC component accepts ChildComponent1 as a parameter and return new component. withCounter can be used in ChildComponent21 which we discuss at the beginning of this tutorial. HOC share incrementCount between components.