How to write a HOC (in 3 easy steps).

Simplest definition of HOC in #reactjs  #javascript #hoc #highordercomponent

  • If you find yourself doing this a lot, you should look for ways to reuse code and solutions that are similar.
  • When it mounts, it fires an xhr request to fetch a user’s details, and then displays them: – – Let’s design another similar component for fetching and displaying a list of tweets.
  • This one will do the same thing: when it mounts, it fires an xhr request to fetch some tweets, and then displays them: – – These two components are very similar; they fetch some data, and then display it, showing a ‘loading’ view while the request is loading.
  • Let’s take the common elements, and put them into a function: – – Now that we have the similar code in a function, let’s make the different code (the url and view) parameters of that function: – – (Notice how we pass the data down to the view).
  • Now, let’s re-implement our two components using this shiny new HOC: – – We’ve cut out a ton of our code duplication, making our solutions simpler and easier to manage.

Learn how to write a Higher Order Component for React in 3 easy steps.

A lot of times when writing software we end up solving similar problems in similar ways. Sometimes we even copy-paste a chunk of code and change just a little bit of it. If you’ve done this before, don’t feel bad; every developer has done this at some point in their career. If you find yourself doing this a lot, you should look for ways to reuse code and solutions that are similar. This principle is called the DRY principle, which stands for “Don’t Repeat Yourself.” The benefit of generalizing your solution is that it allows you to not have to solve the same problem twice!

A mark of a good software developer is being able to recognize patterns in code and being able to write a generic solution for that pattern.

Let’s say we have a component that displays the current user’s profile. When it mounts, it fires an xhr request to fetch a user’s details, and then displays them:

Let’s design another similar component for fetching and displaying a list of tweets. This one will do the same thing: when it mounts, it fires an xhr request to fetch some tweets, and then displays them:

These two components are very similar; they fetch some data, and then display it, showing a ‘loading’ view while the request is loading.

Let’s take a step back for…

How to write a HOC (in 3 easy steps).