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

Did you find this post useful? Show some love!

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... 😞

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.

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 😜

Say your teacher asks the entire class to paint a portrait of their families in some kind of outdoor setting.
Now, you, being as smart as you are, realize that an outdoor setting would almost always mean a blue sky with the sun shining. And any more specific items like a house, a green backyard, a pool, rainbow, trees, family members etc would have to be drawn on top of the blue, sunny background.

So you decide to help everyone in your class out a little and paint a blue, sunny sky (The HOC). And then you draw copies of it, and distribute them among your peers.

The blue sky painting with the sun is useless on its own, but your friends can draw a lot of fun, interesting scenes on top of it and thus make it meaningful (The component fed to the HOC). And of course they all have erasers to adjust minor details like color boundaries (e.g. where the sky meets the ground).
Of course, your background painting won't work for everyone: some of your classmates might want a night scene or the sun in a different position etc. But that's ok. Because before you began this endeavor you realized that you would end up helping a good number of your friends.

ELI5
I (your teacher) sees that you are a curious one. I first answer what components are. Components are sheets of paper, anything you see around that is Paper is also a component.

I point you towards a printer and say this is an HOC sweetie, go ahead use it. You being a smart 5 year old know how to use a printer. I explain further to the class.

  • Paper is a component.
  • Printer is an HOC.
  • I ask you to bring me your component (Paper). You bring a nice clean A4 sheet of Component and put it in the HOC (printer).
  • The class eagerly waits to see the output of the HOC.

Alex exclaims, "It is still a Component, but it is so much more cuter!"

  • This new component has her favourite cartoon character printed on it.
  • You and everyone in the class start finding out various other HOC's in the real world.
  • You and your best friend figure out a Pencil, A shredder, an Eraser are all HOCs.
  • With this great day at school you happily head back to home.

I love that you used my son's name! :) Thanks!

Ben Halpern DEV.TO FOUNDER

Hey there, we see you aren't signed in. (Yes you, the reader. This is a fake comment.)

Please consider creating an account on dev.to. It literally takes a few seconds and we'd appreciate the support so much. ❀️

Plus, no fake comments when you're signed in. πŸ™ƒ

Sometimes components do similar things to other components (or the "lego blocks" of a website). Rather than repeating code, we wrap the components inside "higher order components".

The higher order component handles the similar task, like say, pulling data from a website, and then sends the data down to the child component. This lets us keep each component responsible for a single thing, like showing comments (child component) or grabbing comments (higher order).

<GrabPosts type="blog" />

// GrabPosts sees the type 'prop' and 
// grabs "blog" data from a website
// returns a <BlogPostLoop /> component based on it

<GrabPosts type="comments" />

// GrabPosts sees the type 'prop' and 
// grabs "comments" data from a website
// returns a <CommentLoop /> component based on it

Higher Order Components are the Render Props of 2015 ;)

They are basically functions that take a reference to a component class and return an new component class that does something with the first class.

Redux, for example, uses this to push data from its store into the props of a component.

Classic DEV Post from Dec 17 '17

Do you have any "smart home" projects in the works or in mind?

...

READ POST
Follow @ben to see more of their posts in your feed.
Daniela Jaros
Full stack web developer. Born in Rio de Janeiro, Brazil. Obsessed with sports, movies and technology.
More from @jaro0024
Explain REACT Like I'm Five
#explainlikeimfive
Explain ORM like I'm five
#explainlikeimfive #orm
Trending on dev.to
Web Servers Explained by Running a Microbrewery
#tutorial #beginners #webdev
Understanding JavaScript's Engine with Cartoons
#javascript #beginners #webdev
My Programming Journey: Should You Leave Your Current Job To Pursue Your Goals?
#productivity #beginners #career #discuss
Coding Interview Tips
#career #interviewing #interview #beginners
TIFU(Today I Fuc*ed Up) A Guide from a Beginner to a Beginner
#beginners #rookie #junior
Even Though She Was Bad At Math, She Coded
#shecoded #beginners #webdev
How to Start and Finish Any Web App Project
#beginners #webdev #flask #productivity
I asked my first StackOverflow question
#discuss #beginners #javascript