11 - Higher-Order Components in React - React Higher-Order Components with Example - React Patterns

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello people how are you doing welcome back to another video of the react series today we are going to discuss about higher order components i have got few requests about explaining high order components so i thought why not explaining something very ground up starting with some small examples small real life examples and then getting into the code so in this video you will be learning in and out about higher order components i'm sure at the end of it you really don't have to refer anything else to understand this concept better one quick thing is before we get started i want to request you to subscribe to this channel because i keep sharing lot of good content from my experience that will be useful to you all right so without any further delay let's get started with react higher order components understanding higher order components is really really easy when you understand it with right examples and what we are going to do now we are going to understand this topic with some real life example some easy to understand example so that you will never ever going to forget about higher order components okay so let's get started with those examples right away so first thing that we are going to do this particular example just look into this what we see over here we are seeing bunch of shapes so we have a square over here which is a blue color then we have a star which is a green color and then we have an oval which is a yellow color okay now let's imagine there is a bar in between the burning bar is called turning red okay i have given this name turning red what it does basically it turn each of the shape color to red so irrespective of the shape and irrespective of the color that you know gets as an input to this turning red slab it turns out to become red in color so square become red star become red oval become red so this is the purpose of this one now think about a situation if you have to write the programming logic for doing this turning the color of the shape to red color and if you have to do it for individual shape you will be writing the logic inside this shape you will be writing the same logic inside this you will be writing the same logic inside this so it means the same logic what you are writing you are writing three different times to do what to enhance a property of each of the shape which is nothing but the color enhancing from his existing color to red color instead of that if i can take out that piece of logic that piece of common logic into a centralized place right and i wrap our shapes with this particular logic then the output that we will be getting is the one that we are looking for the changing the color to red at the same time the logic we are not actually coupling with each of this shape rather we are keeping it in a common place so that we can reuse now here you notice i have actually taken few terms right the first time that i have taken is called reuse so we are talking about reusability reusability means you write once and try to utilize it try to reuse it you know again and again so that is the reusability and the second term that i have used called enhancing enhancing an attribute so enhancing an attribute in the sense enhance the attribute of this guy this guy and this guy the attribute is color to something called red so keep these two terminology in mind because when you talk about higher order component will be using this to terminology reusability and enhancing things again and again okay so i hope this particular example was crystal clear to you now in the perspective of this example the left side things and the right side things we can actually call with certain name so if let's come to the react paradigm in react paradigm we can think this as a component we can also think this as a component we can think this also as a component so the left side one we can talk about the input components okay we will will name it as input components for now and the right side piece we will name it as output or the enhanced components and this is the reusable code that we spoke about it so in react terms now if i come these are the components and in between there are some reusable code the reusable code can wrap this input components to create an enhanced component this is a very very basic concept of higher order components in react right so in higher order component in terms of higher order component what we do is like we can we can actually supply some input component to something that something is nothing but a higher order component we will get into that to get an output of an enhanced component now think about it this is a component which is having an attribute called color equals to blue and then if i wrap this component with a reusable code or the higher order component the output that i am going to get is the color change to red so i have enhanced this component this is a very very basic concept very fundamental concept of higher order component and that's what we learn in a series like this where we learn things practically now the second example what i am going to take it's little complex but i am sure that you will have a lot of fun with it so now let's think about the programming world our day-to-day app building work so what we do here is like i have a database which stores some data about movies if you are a movie lover i am sure that you're going to love this example so it has some movie details like you know the movie name you know what is the who is the director how how what is the length of this movie how much star it got how much money it turned what is the cover image of this you know every information that is stored in this particular database that is great now let us say that i i want to kind of display each of this movie details like this card view into my page so this is one component that i can think about it so the component that i am thinking over here is like each of these small boxes is one of the movie details that i am going to show with the covered image and probably the name and things like that that are going to show in terms of card view over here so that is my objective and so i have created a simple movie list component a skeleton component which is having only the jsx part at this point of time and the data to kind of show the actual movie details are lying in the data storage somewhere in the some database that i have to fetch and i have to show now if you all following this series you would have already started you know relating it like how to do it with the you state use effect things like that with the fetch and all i'm sure that you start thinking about this and that's a great thing okay good so next is let's talk about one more thing so what i am looking for it like whenever i am able to fetch the data i will be able to show all the movie details in each of this card this is what i am trying to look for so one way i can do is like i write an api using this api i fetch the data and then push the data as a prop to this kind of skeleton movie list component which you also call the dumb component or the presentational component and with the data i get this movie list completely got populated with the movie details great awesome now the next moment my requirement changes a bit what i am looking for now i am looking for another view i am looking for another component which is instead of a you know this card based component it is a tabular data is a tabular component which is going to show a different kind of data a little bit different kind of data in terms of showing the movie analytics and it is going to show the numbers like this however the data that it is showing it is coming from the same data storage same table from the same data only thing is like it is got computed and it is showing some kind of analytics like for this director you know made this many movies the total run time is this much this is the rating and this is the kind of earning that particular movie has but all these data even this data this covered image and all these data are stored in the data store now to show this one i am doing the fetch from here to here and then showing this one similarly i can always do you know data fetching from the store to this component pass it as a props and can show this one but did you realize that in this case i am going to duplicate the effort of data for fetching in both the components i am going to do in the movie list component i am going to do in the movie analytics component and that is really pain because tomorrow there is another component comes which you want to show the movie details in a different way you know maybe with some kind of visualization it has to again fetch into that component and why to do that you know just copying the same page code three times in three different places for that what i can do i can actually try certain things for example let us think about something sitting in between okay something common sitting in between and this common part can fetch the data from the movie database and after fetching the data it is going to show or help showing the things into a respective component so after fetching this data what this particular component can do is component can make this data available to this particular dumb component or the presentational component now this presentational component can fetch the data from here basically it can get the data from here because this this you know the middle man has already faced it from the database so it is easy to access and after that it is able to show the details basically of you know for all the movies similarly what is this analytics component going to do analytics component is again going to make use of this data and it is going to show the movie analytics over here so the biggest advantage that we have here the fetching part the fetching code we are not duplicating in either of this component we are keeping it somewhere centralized and we are using the data after fetching to pass to this component pass to this component and utilizing this data into each of this component okay so this is the overall story so far now what are the each of these things called let's talk about that this central one is called higher order components okay the center one is called higher order components the the job of a higher order component is to take a component as an input and output ah another component which is like an enhanced component so the component that it takes as an input is called a wrapped component and the component that it returns in in kind of in return is called the enhanced component the highlighter component in react is nothing but a plain javascript function okay it's a plain javascript function that takes and com a component as an argument and return a new enhanced component as a return value as simple as that okay so this is really really not a rocket science this is a very simple thing it's a mere javascript function that takes one component as an argument and returns a new component in the enhanced fashion the example that we have seen here this movie example that you have seen here it demonstrate that it has enhanced this particular component it has taken the component as an input and return the enhanced component with the data similar thing happening at the right side as well so i hope that with this example you are now able to understand what exactly higher order component is and what it is for so the syntax for a higher order component is as simple as this i told higher order component is a plain javascript function so a javascript function has a name so you can name your hierarch component with any name i have given hoc here you can actually give any name of your choice and what it takes basically it takes another one component as an input so why i have this parenthesis so this is the input component and what it returns in return it returns a new enhanced component that is what we are going to use elsewhere so if you take this particular example or the couple of examples that we have given and this particular syntax i am sure that you are now will be able to kind of relate to it very very well any question comes around higher order component what exactly highlighter component is why it is used and how we can make use you will be able to answer each of these questions very well so if you have understood the explanation so far uh it will be very easier for you to even pick up the code examples right so what we learned from the definition so far is like higher order component is nothing but a plain javascript function that takes one argument and the argument is a react component and what it returns a new enhanced component so what we see over here we have created a higher order component that i am going to take you step by step in every step don't worry about it like if you have never seen it before you will understand it completely so first thing i have done is like i have created a plain javascript function const with fetch takes an argument called wrapped component is an arrow function and it has some body inside it that will get in very soon now the name is like with fetch because uh we are going to fetch certain movie data into it and then going to return a new enhanced component you can name it anything this is a naming convention that in general people use for higher order component they start with an bit right you know that is the naming convention but not naturally you have to follow so now we will go step by step i if i expand it the next few things that we are going to see over here there is a something called a class which extend react.component now so far in this series we have seen like functional component we used to create component using functions but most of the usages of higher order component is prior to the react hooks the existence of reacts hook you people used to use uh higher order component a lot and that is the time they used to create components using classes nowadays people don't use classes to create component they use functions to do but you may work in some kind of legacy code where you will be seeing uh components are created with classes so i thought touch base in this case the creating uh component using class that's why we're showing a class game is with switch again you can name it anything i just try to keep it in the same name but you know see the difference here if the class name starts with the capital case that's the convention and it extends something called react.component okay so far with me great now what it does i we told that what we are doing in the hierarchy component is a simple function that takes one component as an input and return a newly enhanced component so if you are seeing here it is returning this with fetch com component that we have created with which class component that we have created ignore this line for a moment now with phase this component will be created so it means that this component if you are creating we have to see what exactly happening inside this component this is where all the magic happen for the higher order component we are returning a new enhanced component so what kind of enhancement we are doing using this uh and what kind of enhancement we are applying in in on the input component thats we are going to see so i am going to extend this one now so if i expand this one i see three major things one is like there is a something called constructor there is something a component did mount and there is something called render so if you are creating a component using class component not using function component things work little bit differently but conceptually they are mostly same so in the class component also you have things like props and state as we have in the functional component so if we are passing or trying to pass any kind of props like properties to this component you have to pass it using constructor and all the states you have to initialize inside constructor in functional component we do it using u state we know that you state hook so if i expand this what i will see i am first initializing the props using the superb super means it is calling the ah constructor of the parent class which is like reactor component right that is provided by react and then what we are doing we are actually initializing a state variable called movies right and initializing with an empty array and in the class component if you want to kind of create a state you have to create it as a as a javascript object that object name you can give anything if you give state you have to set the value of the state using the set state method that is provided by react automatically okay so this is how we have now defined the props and state next thing that comes with the component did mount in functional component we have seen things like use effect which handles side effects now based on the different dependencies we pass to it like state props or any sort of dependency we process to it the use state life cycle actually changes based on what it actually measure that there is a side effect or not similarly the react class components are having certain life cycle methods so that on those life cycle methods when these methods get invoked you can do certain things component bit mount one of the method that actually make sure that your component is completely mounted and inside this function whatever code you write that is going to get executed right after the component mount is successful now our objective with this with fetch component is like we are going to make a call to the movie database using an api to fetch the movie data right so once the component is kind of mounted what we are going to do we are going to make a fetch call so here we are making a fetch call using the using this particular api that i have created which is going to give you the movies information fetch actually returns promises so using them then we are calling response.json which return another promises then we are calling then which returns the data and once i have the data i am using the dot set state you know to set the state value to this movie state over here so now data does move is having this add a movie array which is got set now at this point of time when this component did mount call successfully done this promises a return and resolved successfully the movies will have all the movies data so this part is clear now the last part is about the render so in the functional component when you want to use jsx and return the jsx from the component you do it inside the return in this case you do inside the return function a render function and inside in the form render function you do a return so here everything that we write is pure jsx but i want you to pay special special attention over here what we are doing in this render of the component with fetch component class component we are actually now using the component that we are passing okay and this is where the enhancing happening so taking this component and the data that we have fetched we are using this data as a props this this does state dot movies and actually adding a new probes value to this input component okay so how this component this with phase component enhancing this wrapped component is the width page component making an api call fetching the data whatever the data it is fetching using that data as a props to this particular wrapped component and this wrapped component it is using in his jsx and finally this component this new enhanced components is getting returned from from here right this is what we're doing now our use case is to get the data and pass the data to some kind of skeleton component like this wrapped component whatever the component get passed with the skeleton component so that that skeleton component can take advantage of this data and do anything with it if your use case is something else like you get this particular wrapped component over here and surround it with some other logic over here and then return you do that if your thing is like all the loading indicator like before this component gets loaded whether the data has got loaded correctly or the component got loaded correctly all this logic you want to do in a single place you can do that so the purpose of higher order component is like something common something reusable you want to do along with your you know input component you are going to do that inside this and finally the new enhanced component you are going to return so in this case we are returning this width phase at the end of it great so far with me so this is fine now this final thing is like with phased display name this is optional but it is good to set a display name because at times in the react react debugging tool um it is little difficult to kind of identify which high order component we are working with so in that case if you are giving a display name it is easy to identify okay this is the higher order component i am going i am actually debugging right now this is easy to spot right that's the only purpose we are doing this but net net the story that we told just quickly recap a simple javascript function takes any component any react component and it returns another new component you know new enhanced component that uses this input component to anything that your business logic says in our case the business logic is making an api call get the movies data and pass the movies data to this particular you know input component and render this input component this is my objective that is what i am doing now how am i going to use this okay so let's see that part so for that but i have a movie list component created and i will be showing like how am i using it movie list is our plain old functional component we have seen in this series enough number of times so this is a movie list it takes a props okay the props expects a movie's object it has this jsx value the jsx value is nothing but a div then an h2 and this movies whatever the props that we are getting it is expected to be an array so we are mapping through it and we are actually taking out each of the elements like post title and going to kind of show that you like that if there are 10 movies into this movie object this loop will iterate 10 times and each of the movie object will have the poster title information we are going to show the poster and title information this is very very plain simple but the tricky part is in this export when i am exporting this movie list what i am doing now i am actually wrapping this with my with my higher order component so if you see the higher order component the width fetch i am importing over here and when i am exporting movie list i am passing movie list as an argument to my with fetch function the higher order component and i am returning this now if i just break this one into this two line instead of that for example const hoc equals to this line and then if i do this this both the things are same right both the things are same so what i am doing over here is nothing but i am passing this movie list component as an argument to the you know higher order component and then getting a new enhanced component that this guy returned remember the class component discover return what it returns it returns the jsx which is having the same component along with the movies data passed as a props to this component remember we will go there once movies data on the input component movies data positive props so if the input component is movie list the hoc is having a jsx basically that is having movies list passed with the movies list data that is got from the api call that means it has a props so that props we are getting over here and we are actually going through it and doing all the logic possible logic over here isn't that fantastic it means in my app.js if i just now in import movie list and try to you know use movie list over there like i import movie list and just try to use mobilize what i'll be seeing i'll be seeing the movies are getting listed over there so this is my movie list if you see all the movies are listed here and i'm showing the cover and the title of the movie over here so that my movie list component works fantastically over here so you understood this entire context now if i want to use the same use fetch high order function for another component for suppose movie analytics what i have to do same thing exactly the same thing i'll be creating a new component called movie analytics which takes a props then i actually structure the movies component from here and here i will be writing all the logic to show the table for the movie analytics all the logic for doing like who is a director how many movies he has done all the data i will be getting from this movie's data already so i can create table i can create what sort of html you know element i am looking for in that new component i can create but while returning again i will be passing that com analytics component to with fetch to get a new enhanced component and that enhanced component i will be exporting from here so how many ever new new component i want to create new new presentational component i want to create that is going to use the same data that my high order component is fetching i can very very freely do it i am not using this that the data fetching logic that i have done here in the movie list at all i am not going to use this with fetch data fetching logic into movie analytics uh component i am not going to use that fetching logic into any other components my presentational components are completely independent of the side effect my presentational components are completely independent of data fetching all together that's the purpose guys that's the purpose of higher order component that we had and that's how we used to do before hooks came into picture i hope you got the point and you understood it don't forget to look into the code that you know written over here the link is there in the description of this video so that you know you can understand when you actually go through this video side by side that will be really really useful so i hope you you got the whole context of higher order component now as we have hooks as we have react hooks if you have seen the previous videos we have seen react hooks we have written custom hooks we have done exactly the same thing we have taken our side effects we have taken out reusable pieces into the different react hoops and then we have actually used them elsewhere that's the power right of the reactors that we have understood so as the react hooks have come into the picture slowly the higher order component usage are kind of fading away but there are high chances that you will encounter them in the code that are already written people would not have refactored to use the hooks or your interviewer might ask this question like what is higher order complement what is the real user how will be using can you write one higher component i hope this video clarify these things for you now before i end i just want to recap everything once again because people feel this is a bit tricky com tricky concept to understand but this is really really easy so let me just recap everything once again in next one minute so a higher order component is a plain old javascript function that takes an argument the argument could be a component and it returns a completely newly enhanced component that newly enhanced component use the input component to do something that you would like to do in our case we wanted to enhance it with the movie data that's the reason instead of cop you know creating this movie data in each of the component we are creating in a centralized space in the higher order component and once the data is back we are actually using the same input component and passing the movie data as a props in the jsx of this newly enhanced component and finally returning this newly enhanced component so it means anyone any component that's going to use this higher order component they will create their own you know jsx structure assuming they will be getting a movie's data structure and this movie's data structure will be passed to them as a props how because before you export this particular component you are passing it to our higher order component our higher order component is nothing but a function this is like a function invocation which returns a jsx where in our case exactly the same component along with the movie data that it is passing as a props so that means this guy already getting a props that is the props we are using over here if you have another component like movie analytics you will be doing the exactly same thing you can use a different jsx to show different data that is coming into this movie's data structure guys so that's the beauty of it i hope you understood this one and you're going to make use of it so if you have understood this concept i want you to write what you understood in the comment section of this video please write about it if you have any doubts ask question i make sure i am going to clarify this one so friends was it useful to you if so please please like and share this video and provide the comments i would like to know what is your understanding so please let me know in the comment section like what you understood about higher order components and if you have any further doubts please ask about it in the comment section as well so that i can respond to it and you can learn it better one more thing i keep sharing the periodic quiz into the community channel so don't forget to take that the last quiz was about building a small application you know please go ahead and take that is still open you can still take that thank you very much kashim kashim sheikh who has already taken it and provided the required submission so thanks a lot for doing this i hope that you had your own share of learning all right so before we end i would like to request you to subscribe to the channel if you have not done yet next we'll be coming up with another video from the react series until then take a great care of yourself and keep learning thank you
Info
Channel: tapaScript by Tapas Adhikary
Views: 9,645
Rating: undefined out of 5
Keywords: react, reactjs, javascript, react.js, jsx, react course, react 101, higher-order components, HOC, React HOC
Id: dtwVjJMnOsw
Channel Id: undefined
Length: 30min 12sec (1812 seconds)
Published: Sun Apr 03 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.