Preloader
Drag

Today, I’ll be discussing why we should use the Context API instead of prop drilling.

In a system where you use prop drilling, if you want to use a piece of data on multiple pages, you have to fetch that data repeatedly on each page. This puts a strain on both your backend and frontend servers.

On the other hand, if you use the Context API, you fetch the data or function only once and can send it to all pages.

For example, let’s say you’re designing an e-commerce site, and you need to create the infrastructure for adding a product to favorites. At a basic level, for the favorites process, you need:

  • An array to hold the products
  • A function to add items to favorites
  • A function to remove items from favorites
  • A function to update the database whenever the array is updated

You would also need to call these requirements on the following pages:

  • Categories page
  • Product detail page
  • Favorites page

If you use prop drilling, you would have to add the requirements mentioned above to each page. However, if you use the Context API, you can create a context and a provider, write your requirements within the provider, and set all your pages as children of the provider. This way, you can access your functions and data from each page without writing any repetitive code.

This increases the efficiency of your code and allows you to update all your functions in one place if you need to make changes.

The example I mentioned above is a simple one. If you’re building an e-commerce site, you can use this example not only for the favorites section but also for many other areas, such as user information, cart information, etc. Just imagine doing all of this with prop drilling!

Best regards to everyone. 🙂