How do we use HOC and Context API to handle states in our React projects?

Yağmur Mutluer
Trendyol Tech
Published in
3 min readMar 28, 2022

--

Photo by Tyler Nix on Unsplash

Imagine your project without any data. It sounds like a human without any experience. What’s better in a project than having data? If we can control and use data in every component without passing them down, no one is happier than us.

What is HOC ( Higher Order Component )?

A logic that a wrapper component takes a component and returns a new one. The term comes from functional programming with a name is higher-order functions. If you are curious, you can learn more about the concept from this article.

Let’s explain the usage of HOC with an example.

Assume we have a project that contains user and country searches in a list. The common thing is searching in the list. Do you think we have to write the logic twice? But it isn’t the right way. With HOC, we can write a wrapper component for both of them.

What is Context API?

Have a look at React’s definition.

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

We can understand context’s power in a big project that we need to pass down props in a component tree. But this is not the only way. There are a few state managements libraries are exist with more functionality. One of the famous of them is Redux. I’m not the one who should tell you use one of both. There’s a great article about this two. You can decide with your needs.

If our needs are similar then you don’t have to implement Redux or any other library.

  • Pass and use state in a simple way
  • Make the learning curve shorten for newcomers

Let’s define the definition of context differently. There are two terms called dynamic and lexical scopes. Lexical scope is a unique and isolated variable in the code. If you define a variable with the same name in two functions, the similarity will be the only name. With a dynamic scope, the variable is global and only one. You can read more from this article.

As an international team, we frequently use country information. Let’s look at the product detail example. Discount stamp, price and banner are components that will use country information. The banner can change from country to country to give an example. We can define a top-level component for country information, then child components call and use it.

This one is a simple example. We can use the useState hook inside the HOC. Same level components wrapped with a higher-order component can change and use the state in this way. Besides that, we use this logic when we want to:

  • Separate components and calculations, API calls.
  • DRY ( Don’t Repeat Yourself )
  • Make simple and clean. :)

We use higher-order components and context API to reuse the logic and control the states in a word. I hope this will give you an idea for your project.

Feel free to share your feedback. ❤️

--

--