Skip to content
loading...

re: Explain Higher Order Component(HOC) in React.js like I'm five VIEW POST

FULL DISCUSSION
 

TL;DR

HoC is like Iron Man Suit.

Tony Stark is a person.
When he puts on an armor, he turns into Iron Man but he is a person inside
but can do more (I mean A LOT more like flying and kicking @$$ and stuff).

Details

Iron Man suit is made up of iron gloves, boots, armor, helmet.
Tony with iron gloves, he can fire lasers,
Tony with iron boots, he can fly,
Tony with armor, he can power up his suit,
Tony with helmet, he can control

See the pattern?
So gloves, and boots, armor, and helmet are like HoCs.
Each one gives him more to do.

Tony with gloves, boots, armor, and helmet turns him into an ironman.

const ironMan = withGloves(withBoots(withArmor(withHelmet(TonyStark))));

NOTE

This is not gonna work. Iron Man is rated PG-13... 😞

 
 

Dude this will totally work. Toy aisles are lined with Avengers merch.

 

Thanks, Cat.

LoL, I haven't been to toy stores for years thanks to online shopping sites 😜

 

This is a very creative analogy, for a person familiar with HOCs I totally get it. I just worry it might have missed an important detail which might not be that obvious to a newcomer.

HOC is not a component but just a mere function which happens to return a component. 🧀 , πŸ‘’ would rather be the output of the HOC.
When we write β€˜withCompX(compY)’, we mean this HOC will wrap compY with CompX.

The examples below are similar in logic, the only difference is that one is done real-time and the other is done statically/by hand.

// by hand, not so cool 😎 
const MyComp = (
 <CompX>
  <CompY/>
</CompX>
);

const withX = (Comp) =>
   <CompX>
     <Comp/>
   </CompX>;


const MyOtherComp = withX(CompY)

// MyComp and MyOtherComp are now same with the only difference is that MyOtherComp was generated on the fly 
 

Thanks Kushan.

I see where my analogy breaks down as I was using each object(gloves, helmet, etc) as a concrete component, not as something that enables Tony to do something.

code of conduct - report abuse