The React Context API- You, Your friends, and the Burj Khalifa.
Published: 2023-01-21 10:40:57


These days, even the smallest software application/software product has learnt to become more complicated by the end of the third iteration sprint- in terms of technical implementation and requirements specification, but so also, we software engineers and system designers have also continued to discover and innovate new ways and tools for managing such complexities.

And, just incase you are wondering if this was written by an AI (….laughs), NO!, and since i have pre-emptively mentioned it, i would like to add that i am one of those who now believe that the age long question of whether computers can think should now be modified into the question of whether AI can be creative! The next few years would surely be some of the most exciting times of our lives.

But Samuel, this is not an article on Artificial intelligence or the rise of the machines, so please, can we move on to the business of the day?

Sure! no more BS, i promise.

Enters React Context API.

If you are reading this, then chances are that you already know a thing or two about how the web works, or at least how this website was likely built, a high level overview at the least and that means that you know that most custom websites have a client frontend, a server backend, and a database.

In modern development, communication between these three layers are largely facilitated by application programming interfaces(API’s). The React context API is however a special kind of such API. The overall purpose of all API’s as we know it remains that of facilitating and enabling efficient communication between the various parts of our application. For an API like the React Context API, this purpose finds execution within the frontend when we build our application frontend with react.

When we build the user interface of our application in react, all we do is build our UI from stand alone components that we then assemble together to create the complete user interface, just as one builds a skyscraper(UI) from lego blocks(components). For a simple application, and depending on the data model one uses, props may suffice as an appropriate means for passing data between the various components that make up our UI.

But first, why would you want to ever pass data across or between components?. Because a particular data, depending on the complex nature of the software, and the business need of the application, may have to be displayed in more than just one location on our UI.

For illustration purposes, imagine that we decide to build a contact application that gives a user an interface screen which shows an input form for users to add new contacts, and a sort of summary card which displays the total number of contacts in the users contact list. Let’s also assume that on the same UI, a user can see a statistical breakdown of contacts in terms of number of males and females right on their Interface.


Let our interface look like that, and yeah, its not the best looking interface, but you know i tried at least(Lol). From the interface we have three <card/> components that render our total number of contacts, number of girls, and finally number of boys.

We have an entry form with inputs for our contacts name and email. Somewhere on this form should be a radio input for also choosing if a particular contact is M or F. To the right of our form is a <display/> component that displays a sort of <ContactCard/> component for all our contacts as we add them from the form. So, the user flow is thus:

You the user bump into an old friend, and after your pleasantry exchange, you decide to use our amazing contact app. You login and you see the screen above, and so you enter your old friends name, email and sex and then proceed to add them as a contact. As you click the add button, the Contact card display session gets updated with a new <ContactCard/> component, just as the stat displays too gets updated accordingly.

Now, the question that frontend engineers always have to answer when designing or building similar applications like this one is always that of how you ensure that each component data is updated accordingly, and almost simultaneously throughout the interface.

Before the arrival of the context API, engineers have always had to use props, which is a way of passing data from parent to child components in react. So, using props we will have to first elevate our state to the topmost component which would serve as our parent component- Lets call this the <App/> component.


From the code snippet, i have omitted all imports for hooks, and of-course styling for the components.

From the code, we are fetching the contacts within our parent component, saving it to the data state and then passing the entire state as props to the various components that needs them. Each of the three components shown in the code as receiving the props would in turn pass the props to their own child components accordingly, and depending on how deeply nested our component structures are, especially for large projects, keeping track of this props-hell and how the data changes(if we have multiple states), can indeed prove to be a nightmare for any developer. This nightmare has a fancy name in software engineering parlance- prop drilling! And yes, even though we seem to be terrible at finding a perfect name for variables in our code, we are very good in finding perfect names for situations like this, and yes, because we are also lazy, we find appropriate solutions too-React context API.

With React context API, we do not have to prop drill, and even though this is a perfect solution, i also belong to the camp of users who believe that the react context API, although a valid tool within the react toolbox, should not be employed for all cases, as it might be an over kill for a situation where simply using props would suffice perfectly. As a rule of thumb, i only use the react context API for projects with at least ten different components that need access to one data and the functions that alter that data. You can choose differently. With the react context API, we can do things differently in a more revolutionary style.

For me, i always like to maintain the following folder structure for all of my frontend project:


and at this point, the context folder will house all of my react context API node points.

Before i proceed to showing you how the context API works, let me try to give a high level description of what problem it eliminates by using a simple analogy.

Imagine that you and your friends have decided to come together to build a very large model of a house using lego blocks. To make your progress faster, you and your five friends decide that you would like to share tasks, while you are focused on building the parlour, another friend of yours should focus on building the rooms, while another should focus on building the roof, toilets, and playground area respectively.

Since you all have decided to focus on various parts of the house, you would all then combine your results in the end to sort of have the finished house model. Sounds like a great plan!

In this analogy, the building is our application, the parts that each one of you and your friends concentrate on building independently before combining your results are the components of our application.

With the props model, even though you and your friends are working independently, and maybe fetching your lego pieces from a single lego bag, your friend who is working on the roof somehow would ask another of your friend working on the parlour floor to please tell the one who is working on the fences or gate- and maybe closer to the lego box to please pass them the lego pieces that they need. This means that, every time that the guy who is working on the roof needs a lego piece, he or she would have to receive it from the person who is closest to the lego box, who must then pass it further through three other friends at the parlour, rooms, and toilets, before it gets to the guy on the roof.

For a small house, this may not be a problem, but imagine you and say 10,000 other friends trying to build a lego model for burj khalifa which has 163 floors using this prop model!

The context API simply provides a leaner alternative. All you have to do is create a context API which would have a single node point that can be imported from anywhere within your project. Using our analogy, the context API would be like having a black box machine with buttons that pops out a lego when pushed. Each one of your friends can have access to this button in real time, and would simply push it whenever they need a lego. The button allows all of your friends to push it at the same time and get their lego simultaneously.

Now, armed with that analogy, lets create a context API for our contact application. which will serve as the magic button that when pushed by our components, yields data simultaneously.

The implementation:


With the context API for our contacts now exposed, every component within our project can instantly access it- without prop drilling across components. With this, each one of our <Card/> and <ContactCard/> components can then directly access the contacts data without needing to go through the <App/> component, <StatDisplay/>, or <Display/> components respectively.

All you would need to do is import the useContext from ‘react’ and then the ContactsContext from ‘../context/ContactContext’.

And then; const {data} = useContext(ContactsContext).

Viola! that component would instantly have access to the state data, and so, no matter where the component is used(regardless of how deeply nested it is within the component tree, you do not have to care what props are delivering it.

React Js Tutorials
React Hook
Java Script
React Context Api