# Higher Order Components In Reactjs

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,
1. const sum= (number1,number2)=>{
2.    return number1 + number2;
3. }
The above function is simple, it accepts two input numbers and returns the sum of those two numbers.

Now we can take another function,
1. const calculator = (operationType) => {
2.     if (operationType === “sum”) {
3.         return sum;
4.     }
5. }
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.
1. 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.
1. 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
1. Export default class LikesCount extends component {
2.     Constructor(props) {
3.         This.state = {
4.             Likes: 0
5.         }
6.     }
7.     handleClick = () => {
8.         this.setState({
9.             likes: this.state.likes + 1
10.         })
11.     }
12.     Render() {
13.         Return( < div > {
14.             this.state.likes
15.         } < br / > < button onClick = {
16.             this.handleClick
17.         } > Like < /button> < /div>)
18.     }
19. }
1. Export default class CommentsCount extends component {
2.     Constructor(props) {
3.         This.state = {
5.         }
6.     }
7.     handleClick = () => {
8.         this.setState({
10.         })
11.     }
12.     Render() {
13.         Return( < div > {
15.         } < br / > < button onClick = {
16.             this.handleClick
17.         } > Add Comment < /button> < /div>)
18.     }
19. }
App.js
1. Function App(){
2.    Return(
3.    <div>
4.       < LikesCount/>
6.    </div>
7.    )
8. }
If you run this code, we can see the total number of likes and comments, initially 0, and the button click action will increment both by 1.

Now, if we see here both are following the same logic, which means both comments are doing increments of the count by 1 on every button click action.

Two things we can consider here, duplicate code for same logic and for large enterprise websites it may a performance issue.

So, by using HOC concept we can simplify this code very simple and understandable.

Let create a new component HOC.js
1. Const HOC = (Component, data) => {
2.         Return class extends component {
3.             Constructor(props) {
4.                 This.state = {
5.                     Count: 0
6.                 }
7.             }
8.             handleClick = () => {
9.                 this.setState({
10.                     Count: this.state.Count + 1
11.                 })
12.             }
13.             Render() {
14.                 Return( < Component CountNumber = {
15.                         this.state.count
16.                     }
17.                     handleClick = {
18.                         this.handleClick
19.                     }
20.                     />)
21.             }
22.         }
The above code accepts two arguments, the first one is component and 2nd is data. Then we applied the same logic which was already available in the other two components.

Let’s rewrite the LikesCount and CommentsCount components to run with this HOC component.

LikesCount.js
1. Import HOC from “./HOC”;
2. class  LikesCount extends component {
3.    Render(){
4.       Return(
5.          <div>
6.             {this.props.CountNumber }<br/>
7.             <button onClick={this.props.handleClick}>Like</button>
8.          </div>
9.          )
10.       }
11.    }
12. Const enhancedLikesCount = HOC(LikesCount); // we created new component which uses the HOC Component.
13. Export default enhancedLikesCount;
1. Import HOC from“. / HOC”;
2. class CommentsCount extends component {
3.    Render(){
4.       Return(
5.          <div>
6.             {this.props.CountNumber }<br/>
7.             <button onClick={this.props.handleClick}>Like</button>
8.          </div>
9.          )
10.       }
11.    }
12. Const enhancedCommentsCount = HOC(CommentsCount); // we created new component which uses the HOC Component.
App.js
1. Function App(){
2.    Return(
3.       <div>
4.          < enhancedLikesCount />
{"ft_lang_label":"__label__en","ft_lang_prob":0.7564643,"math_prob":0.8746127,"size":5035,"snap":"2021-31-2021-39","text_gpt3_token_len":1218,"char_repetition_ratio":0.1701451,"word_repetition_ratio":0.23372093,"special_character_ratio":0.28123137,"punctuation_ratio":0.14669926,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.97634387,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-09-21T16:58:41Z\",\"WARC-Record-ID\":\"<urn:uuid:58e42d00-1de5-4e84-82d6-a95a83a0562a>\",\"Content-Length\":\"163716\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:254dd769-badd-477d-9b1b-f172bf2b4f9a>\",\"WARC-Concurrent-To\":\"<urn:uuid:45b92872-ba44-446f-8c7e-c042b0948d7e>\",\"WARC-IP-Address\":\"40.65.205.118\",\"WARC-Target-URI\":\"https://www.c-sharpcorner.com/article/higher-order-components-in-reactjs/\",\"WARC-Payload-Digest\":\"sha1:OHYBPILJX4624Z6VZ3NCWUHP3FNOMBLK\",\"WARC-Block-Digest\":\"sha1:QLLWJYCF5IKGD5X6YHKL7GC6ZQREHE4F\",\"WARC-Identified-Payload-Type\":\"application/xhtml+xml\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-39/CC-MAIN-2021-39_segments_1631780057225.57_warc_CC-MAIN-20210921161350-20210921191350-00126.warc.gz\"}"}