DEV Community

Discussion on: Explain Higher Order Component(HOC) in React.js like I'm five

Collapse
 
dance2die profile image
Sung M. Kim • Edited

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... ๐Ÿ˜ž

Collapse
 
cat profile image
Cat

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

Collapse
 
dance2die profile image
Sung M. Kim

Thanks, Cat.

LoL, I haven't been to toy stores for years thanks to online shopping sites ๐Ÿ˜œ

Collapse
 
kepta profile image
Kushan Joshi • Edited

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 
Collapse
 
dance2die profile image
Sung M. Kim

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.

Collapse
 
jaro0024 profile image
Dani Jaros

Awesome! Thanks!