ReactJS Tutorial – 34 – Higher Order Components (Part 2)
Video Title: ReactJS Tutorial – 34 – Higher Order Components (Part 2)
In the last video we saw that there was a need to share common functionality between components and I mentioned higher-order components will help us with that but what exactly is a higher-order component let’s talk about that in this video let’s begin with what is a higher-order component a higher-order component which
Will be referred to as hoc from now on is a pattern where a function takes a component as an argument and returns a new component in simple code it will look something like this Const new component is equal to a function called higher-order component and we pass in the original component as
An argument typically an hoc adds additional data or functionality to the original component so the new component can also be referred to as enhanced component if you were to understand this from a non technical point of view you have Iron Man is equal to with suit passing in Tony Stark as a parameter
Here Tony Stark is the original component with suit is the function that will enhance Tony Stark and return Iron Man which of course is the enhanced component from react point of view we have a function which accepts the original component adds functionality and returns an enhanced component or in
Other words we have the hoc pattern alright now that we know what the hoc pattern is we can head back to vs code and learn how to implement a basic hoc and then implement it for the counter example we had from the previous video let’s start with the bare minimum code
For an hoc I’m going to create a new file called with counter dot J’s not going to worry much about the folder structure I’m going to create it in the components folder with counter jazz the filename is an hoc convention which we will discuss in a
Bit now let us create our hoc first let’s import react import react from react next let us create a function the function will of course be an arrow function Const updated component is equal to an arrow function the hoc accepts the original component as its parameter
The HSC also returns a new component so within the function body let’s create a new component class new component extends react dot component in a class component the render method is a required method but what do we render we simply return the original component so render and return
The original component now that the new component has been defined we return the new component in the error function returned new component and there you go we have a very first higher-order component it is a function that accepts the original component and returns a new component this HSE though doesn’t really
Add anything to the original component let’s change that on the original component in the JSX I’m going to add a prop mean is equal to vishwas now to be able to use this hoc function we need to export it export default updated component now let’s apply this hoc
Pattern to our click counter and our counter in click counter I will import updated component from with counter and while exporting I will call the updated component function passing in the click counter component let’s do the same for hover counter as well I’m going to copy this import
Statement paste it in our counter and explore the updated component with our counter so what we are doing here is instead of exporting the click counter or the hover counter component we export the higher-order component the hoc in addition to be the click counter or the
Hover counter now has a new prop called name so in both the components we can actually render this prop so in the JSX this dot props dot name and the same in hover counter as well if you now save the files and take a look
At the browser you should be able to see the prop being rendered which was in the button and vishwas in the heading so our hoc injects a named prop to any component required for our counter example though that is not really what we want we want the counter
Functionality to be shared amongst the components so let’s modify our hoc I will copy the constructor and the increment count method from the click counter component into the hoc so copy the code which has to be shared and paste it in the HSE the current state and the increment
Count method is the common functionality we want to share so the new component now maintains a count state and a method to increment that state this is the common functionality we want to share I will remove the same piece of code from both click counter as well as hover counter this will avoid
Duplication of code now in the hoc we need to pass down the state and the increment count method as props so that the original component can make use of that functionality I will remove the name prop and instead add count is equal to this dot state dot count and
Increment count is equal to this dot increment count we can now make use of these props in click counter and have a counter in click counter we are going to destructor count and increment count from this dot props and I will get rid of the state in the onclick handler
It is now going to be just increment count I have lots of get rid of the meme that was being rendered now let’s repeat the same for our counter as well Const count comma increment count is going to be the structure from this dot props I will remove this keyword from on mouse
Over event handler and also the name prop if we now save the files and take a look at the browser you should see that both the counter components are working as before but the difference now is that we are reusing code rather than duplicating it that is what hoc s bring
To the table let me go over the code one more time so that you get a proper understanding of how hoc s work I will begin from Abdo J’s here we have included the click counter component the clip counter is defined in click counter dot JS file now over here you can notice
That we are exporting the updated component hoc passing in the click counter the updated component is defined in with counter let’s take a look at that file the updated component is a function which accepts a component or an original component as its parameter and returns a new component in our case the
Original component refers to the click counter the new component has functionality to maintain the state of account property and also a method to increment that current property both of them are passed as props to the original component the original component enhanced with these props are then returned the control goes
Back to click counter where the count and increment count probs passed in from the HSE are be structured and used in the return statement so the hoc is basically taking care of maintaining the state and incrementing it when you click on the button the count is incremented and displayed in
The UI the same execution flow also happens for the hover counter component but what you should know is that both the components received separate state incrementing the count in click counter will not affect the hover counter and vice-versa so that is how an HSE works it is a function that accepts a
Component and returns an enhanced component now let’s talk about the naming convention the component and functions you typically see are different from what I have used so let me change them the function and the file name is usually the same it indicates the functionality that will be added to the components so Const
With counter and export the same the original component is usually referred to as wrapped component that is the component wrapped with the HSE so let’s change the parameter name and the return statement the new component is usually the same as the function name but in Pascal case the
New component will be with counter and we will return the same in click counter and hammer counter we are going to change updated component 2 with counter which is the function name with the counter make sure to import it and repeat the same in our counter with
Counter with counter you can now read the export statement as with counter functionality export the hover counter component now if there is no rule which tells you to name your components or hoc s this way but this is kind of the convention used in most of the videos
And articles we have two more points to discuss about hoc s but for now just keep this in mind an HSE is a pattern where a function accepts a component and returns an enhanced component the HSE pattern is used to share common functionality between components without having to repeat the code
All right thank you guys for watching don’t forget to subscribe I’ll see you guys in the next video
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
You are awesome! Thank you very much for all of your videos.
why can't we just simplify it like this? const UpdatedComponent = OriginalComponent => { return <OriginalComponent name='Vishwas' />};
Great video, thank you!
The way you explain the HOC is clean and simple to understand. Thank you so much for all your videos.
Thanks for your clear explanations. Why is inheritance not simpler in such a scenario? We could implement a CounterBaseComponent and extend it to a ClickCounter and HoverCounter, isn’t it? Are there scenarios where the HOC or render-patterns are better suited than inheritance? I can imagine that the HOC can be used to wrap components with additional functionality that does not entail changing the WrappedComponent, like memoization or error handling or the like. Makes sense?
Good description: HOC takes the component and returns enhanced component
const WarMachine = withSuit(JamesRhodes)
Instead of creating HOC, can we not extend component?
Best way to teach HOC… Kudos to you !!!!!
I did not understand why you used 'const' datatype while destructuring the props ?
And since count is now an integer datatype with value initialised, how can that be increased?
props are supposed to be immutable, right? then how come we change them with button clicks in this example
Can we create a newcomponent as a functional component instead of class?
Every other explanation I found on the internet was really difficult to grasp (even worse with TypeScript examples). But your explanation was so easy to digest. Thank you Vishwaz!
Thanks for sharing this video learned a lot thanks
good example that iron man with stark . .
explained very well please make more videos like this (keeping shorter and easy to understand).
syntax: enhancedComp = hoc(comp)
HOC is a function, that takes 1 component as argument and returns enhanced new component.
In export statement, need to export all the components, that are going to use common code, as that hoc component method.
Hoc method
In hoc, we need to pass ‘state & increment method’ as props, so original component can make use of it.
In components that wanna reuse code:
Will take from props. So no ‘this. ’ or state variable usages (mean – no local). Export with hoc component.
Calling these components is normal way.
Thanks you so much codeevolution! you always delivery it very clean
what is this
Cont we do this using hooks instead of HOC?
I ADORE your tutorials. I learn a lot.
amazing
Is that equal to custom hook in react function component
Plz made this video with function based components , it's kind request.
How to use HOC in functional component? I have tried it's giving useState error
Awesome explaination…
why he used incrementCount = () => {} instead of a normal method like incrementCount(){} ?
I started the journey to become a better / serious dev and got to know design patterns
…so this HOC is a decorator?
Sir i cud not understand the flow. When <ClickCounter> from App.js called, in ClickCounter component will it be exported to UpdatedComponent first or render() method will be called first for onClick incrementCount handler?
Hi, thank you very much, the explanation is very useful, I have a question: Why the use of the "new" keyword isn't required in the hoc, when the enhanced component is returned?
You are awesome Vishwas. Thanks a lot ♥
Love from Pakistan💕
Thanks!
why using class component you made me confused just stick to functional component dude
That was explained so well – thanks so much!
My man, this was excellent 🙂 As soon as my paycheck arrives, I will support you 😀
Very useful tutorial many thank you
Tenq-u ma-frend!
Thank you so much, you made it ez pz ❤️