Everything you need to know about React’s Context API

Everything you need to know about React’s Context API

In this article, I will walk you through the basics of the new Context API and why to use it in your next React based project.

In this article, I will walk you through the basics of the new Context API and why to use it in your next React based project.

React is one such UI library which gets frequent upgradation in terms of new features and concepts within months. One such additional concept or feature in version 16.3 gives us Context API which is an upgraded version of old concept of context in React which allow components to share data outside the parent-child relationship.

Let’s dive in!

Why do you need Context API in React?

Before we dive into the reason why React upgraded to Context API, let’s first be familiar with some basic terminologies which are used to introduce data manipulation and updation in React.

In React, Data is updated and manipulated by using some terms which we called as props and state.

Props or properties can be understood as the data or information that is being passed to the child component from a parent component.

While state can be easily understood as the data which is being managed within the component itself.

So if each component manage it own state, how could you share data between nested components? Yes, it is true that we have props to pass the data but that only works in parent-child relationship case.

For an instance, let’s take an example of an app which is composed of different types of nested components:

As seen in Image above, Child2 is the children of Child which is also child of Parent. That makes Child2 as the grandchild of Parent.

Now, let’s play with some code to understand it in a more simplest manner:

class Parent extends React.Component {
 state = {
 value: ‘Some value’
 render() {
 <Child value={this.state.value} />
const Child = (props) => (
 <Child2 value={props.value} />
const Child2 = (props) => (

In the above example, we are sending value from parent component (Parent here) through its child component Child, which is then supposed to be used inside component Child2. Here, Child component doesn’t care about the value (prop), it’s only passing down the prop to be used within component Child2. Now, this example might seem simple to you and you will wonder what’s the problem with that.

Let’s imagine for a second, if we not only have a Child component but Grandchild1 and Grandchild2 or further more components between Parent and Child2. In such case, you would need to pass the props further down to each of these components of the tree. But, by the definition of props mentioned above, value can be passed only in between Parent and Child.

Such kind of problem which could be a havoc for React performance is known as Prop drilling. In simpler terms, it relates to the passing down of props from the upper level i.e Parent to lower level components such as Child, Grandchild etc. in the component tree, where components in between doesn’t care about these props.

Although, you have libraries such as Redux to mitigate this kind of complexity but it’s worthless to use Redux in this case as it will make your app’s logic more complex. Nevertheless, this is where the concept of Context API in React comes into play.

When should you use React’s new Context API?

Using Context is the best fit for the use case where your codebase consists of lot of components that depends on a single piece of data, but are nested deep within the component tree.

Following image will give you an idea as in how deep your upper level, middle level and lower level components can be nested within a component tree:

Things you need to be familiar with before using React’s new Context API

As mentioned above, React’s new Context API provides a way to pass and store data down a React component tree without writing it into every layer of the component hierarchy. It does so by leveraging on two types of components:

Provider — The Provider component is used in higher hierarchy of the tree. It accepts a prop called as Value. It acts as a root component in the hierarchical tree such that any child in the tree can access the values that are provided by the context provider.

render() {return (
<Provider value={this.state.contextValue}>

Consumer — As the name implies, consumer consumes the data which is being passed, irregardless of how deeply nested it is located in the component tree. That means, Consumer don’t have to be necessarily be the child of Provider. Instead, it can access data from anywhere down the component tree.

A consumer renders the data by using a render prop API.

render() {return (
{contextValue => <Child arbitraryProp={contextValue} />}

How to use Context in your React Application?

Now that you are pretty much familiar with what’s up to the new Context API, now is the time for you to understand how to use Context in an application.

In React, you have a predefined function to create a Context:

const Context = React.createContext();

React.createContext is used to initialise the Context and it’s passed the initial value. It returns an object with a Provider and a Consumer. Providers and consumers come in pairs, that is, for each provider, there is a corresponding consumer.

The examples explained above are pretty much simpler to understand. Though, you always will have to play with more complex data and find a way to store that data down in the component tree so that other components could use it.

Let’s now re-implement the above example with the context API:

const Context = React.createContext();
class Parent extends React.Component {
state = { x: 1 };
handleContextChange = x => this.setState({ x });
render() {
const contextValue = {
data: this.state,
handleChange: this.handleContextChange
return (
<Context.Provider value={contextValue}>
const Child = props => <div><GrandChild/></div>;
const GrandChild = props => (
{({ handleChange, data }) => (
<button onClick={() => handleChange(2)}>Change</button>
<Child2 text={data.x} />
const Child2 = props => <p>{props.text}</p>;

In the above code snippet, we have started by initialising a context. Then we have use it in the top hierarchy which belongs to the component Parent. The State of Parent component is the value of Context.Provider. Upon changing the state, the Context.Provider gets a new value. Parent component is also used as the storage of our storage of the state so that the context can pass it down the hierarchy.

In the component GrandChild, we have used the Context.Consumer which receives a function via its children render prop. Upn changing the value of Context.Provider, this function is invoked repeatedly and renders with the new value finally.

Here, component Child which is between Parent and GrandChild is not aware about the whole context arrangement. Same is with component Child 2 and button element as they also don’t know about the context. These components just receive the data and the changeHandler function passed via their props and can use them further as any other prop.

Final Words

React’s new Context API is definitely not an alternative to the state management libraries such as Redux or MobX. Neither, it relies on passing a context down the component down the component tree. Instead, it provides a provider-consumer component pairs to communicate between the nested components in the hierarchy.

The top level components provide the data and the lower level components consume it without having to pass the data down the component hierarchical tree level-by-level.

With this article, you are good to start with using the React’s Context API in your apps. If you further want more relevant information about the API, don’t forget to go through the official documentation.

What the difference between REST API and RESTful API?

What the difference between REST API and RESTful API?

Representational state transfer (REST) is a style of software architecture. As described in a dissertation by Roy Fielding, REST is an "architectural style" that basically exploits the existing technology and protocols of the Web. RESTful is typically used to refer to web services implementing such an architecture.

The short answer is that REST stands for Representational State Transfer. It’s an architectural pattern for creating web services. A RESTful service is one that implements that pattern.

The long answer starts with “sort of” and “it depends” and continues with more complete definitions.

Defining REST

Let’s start by defining what REST is and is not. For some, REST means a server that exchanges JSON documents with a client over HTTP. Not only is that not a complete definition, but it’s also not always true. The REST specification doesn’t require HTTP or JSON. (The spec doesn’t mention JSON or XML at all.)

The Origins of REST

Roy Fielding introduced the REST architectural pattern in a dissertation he wrote in 2000. The paper defines a means for clients and servers to exchange application data. A key feature is that the client doesn’t need to know anything about the application in advance. The link is to chapter five of his paper. While the entire dissertation describes the hows and whys of REST, that chapter defines the architectural pattern.

Fielding doesn’t mandate specific requirements. Instead, he defines REST regarding constraints and architectural elements.

REST’s Architectural Constraints

Here is a summary of the constraints.

  • Client-server – REST applications have a server that manages application data and state. The server communicates with a client that handles the user interactions. A clear separation of concerns divides the two components. This means you can update and improve them in independent tracks.
  • Stateless – servers don’t maintain any client state. Clients manage their application state. Their requests to servers contain all the information required to process them.
  • Cacheable – servers must mark their responses as cacheable or not. So, infrastructures and clients can cache them when possible to improve performance. They can dispose of non-cacheable Information, so no client uses stale data.
  • Uniform interface – this constraint is REST’s most well known feature or rule, depending on who you ask. Fielding says “The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.” REST services provide data as resources, with a consistent namespace. We’ll cover this in detail below.
  • Layered system – components in the system cannot “see” beyond their layer. So, you can easily add load-balancers and proxies to improve security or performance.

A RESTful service is more than a web server that exchanges JSON, or any other, documents. These constraints work together to create a very specific type of application.

Applying the Constraints

First, the client-server, layered systems and stateless constraints combine to form an application with solid boundaries and clear separations between concerns. Data moves from the server to the client upon request. The client displays or manipulates it. If the state changes, the client sends it back to the server for storage. Fielding specifically contrasts REST with architectures that use distributed objects to hide data from other components. In REST, the client and server share knowledge about data and state. The architecture doesn’t conceal data, it only hides implementations.

The cacheable and uniform state constraints go one step further. Application data is available to clients in a clear and consistent interface and cached when possible.

So, that’s the technical definition of REST. What does it look like in the real world?

RPC Over HTTP vs. RESTful

Often when someone says that a service “isn’t REST,” they’re looking at the URIs or how the service uses HTTP verbs. They’re referring to REST’s presentation of data as a uniform set of resources.

This distinction is sometimes framed as a difference between remote procedures calls (RPC) and REST. Imagine a web service for listing, adding, and removing, items from an e-commerce inventory.

In one version, there’s a single URL that we query with HTTP GETs or POSTs.  You interact with the service by POSTing a document, setting the contents to reflect what you want to do.

Add new items with a POST with a NewItem:

POST /inventory HTTP/1.1
    "NewItem": {
          "name": "new item",
          "price": "9.99",
          "id": "1001"

Query for items with a POST and an ItemRequest:

POST /inventory HTTP/1.1
    "ItemRequest": {
          "id": "1001"

Some implementations accept a request for a new item with a get, too.

POST /inventory?id=1001 HTTP/1.1

We also change or delete items with a POST and an ItemDelete or ItemUpdate.

POST /inventory HTTP/1.1
    "ItemDelete": {
          "id": "1001"

This isn’t REST. We’re not exchanging the state of resources. We’re calling a function with arguments that happen to be in a JSON document or URL arguments.

A RESTful service has a URI for each item in the inventory.

So, adding a new item would look like the example above.

POST /item HTTP/1.1
    "Item": {
          "name": "new item",
          "price": "9.99",
          "id": "1001"

But the similarities end there. Retrieving an item is always a GET:

GET /item/1001 HTTP/1.1   

Deleting is a DELETE:

DELETE /item/1001 HTTP/1.1  

Modifying an item is a PUT:

POST /inventory HTTP/1.1
    "Item": {
          "name": "new item",
          "price": "7.99",
          "id": "1001"

The difference is important. In REST, operations that use distinct HTTP actions. These verbs correspond directly to the activity on the data. GET, POST, PUT, DELETE and PATCH all have specific contracts. Most well-designed REST APIs also return specific HTTP codes, depending on the result of the request.

The critical point is that the URIs operate on the data, not on remote methods.

But there’s another reason why the resource model is essential.

REST vs RESTful and the Richardson Maturity Model

When you model your URIs after resources and use HTTP verbs you make your API predictable. Once developers know how you defined your resources, they can almost predict what the API looks like. Here again, the emphasis is on understanding the data, not the operations.

But even if you can’t make the API entirely predictable, you can document any REST service with hypertext. So, each item returned in the inventory app would contain links for deleting, modifying, or setting the inventory level of the resource. Fielding says that before a service is RESTful, it must provide hypertext media as part of the API.

Many sites don’t meet this requirement but are still called REST. Fact is, many sites break the rules in one way or another. So many that Leonard Richardson created a model breaks down REST into levels of compliance

We’ve already covered the source levels:

  • 0 – exporting an API over HTTP with methods called with arguments
  • 1 – Exporting resources instead of methods
  • 2 – Proper use of HTTP verbs
  • 3 – Exporting hypertext with objects that make all or part of the API discoverable.

Richardson’s model is his own, and it doesn’t map directly into Fielding’s spec. Since Fielding requires level three, he would say that most apps aren’t REST anyway.

The point is many services that we colloquially refer to as REST, technically aren’t.

REST vs RESTful: Does It Matter?

So, does the REST vs. RESTful comparison matter? Probably not. How well your architecture complies with an arbitrary standard isn’t as important with how well it suits your needs and can grow with your business.

The REST architectural pattern has many advantages. Fielding designed it for the web and, 18 years later, most of the constraints he had in mind are still with us. In 2000 we didn’t have Android or the iPhone. IE5 had 50% of the browser market share. It’s biggest rival was Firefox. But Fielding recognized what online applications needed and how web clients would evolve from HTML display engines into complete applications. The tools we use today have grown to suit REST, not the other way around.

Thank you for reading. Hope this tutorial will help you!

Why ReactJS is better for Web Application Development?

Why ReactJS is better for Web Application Development?

Web Application Development is the point of contact for a business in today's digital era. It is important to choose the right platform for Web Application Development to build a high end Web

Web Application Development is essential for a business in today’s digital era. Finding the right platform for Web Application Development is important for building an effective Web Application that can enhance the overall customer engagement. Here’s what makes ReactJS a better option for building your next Web Application.

React and APIs - Full Tutorial - Hacker News API Application

React and APIs - Full Tutorial - Hacker News API Application

Learn how to use APIs with React in this intermediate tutorial. We're going to be creating a small application in React that calls the Hacker News API. We'll be looking at React memo, Axios (to make API calls), styled components, and finally we will test our work using React Testing Library.

React and APIs - Full Tutorial - Hacker News API Application

Once we have done all this we will run our application through Lighthouse (a browser extension) that allows us to test for accessibility, performance and so much more. We will be making 500+ automated API calls in this application, and I want to show you how to use memo with React so that we can avoid making multiple network calls if we already have the data.

💻 Code: https://github.com/karlhadwen/newsreader

⭐️ Course Contents ⭐️
⌨️ (0:00:00) Introduction (what are we building?), tech stack talk
⌨️ (0:01:50) Using create-react-app as our base
⌨️ (0:03:30) Stripping out the files & content that we do not need
⌨️ (0:05:00) Refactoring to named exports
⌨️ (0:08:35) Modifying our .env file
⌨️ (0:09:15) Scaffolding our application
⌨️ (0:10:15) Looking at the Hacker News Api
⌨️ (0:11:50) Looking at all the news article Ids
⌨️ (0:12:58) Adding Axios using Yarn
⌨️ (0:13:00) Creating our hnApi.js service file
⌨️ (0:15:07) Adding the ability to get all story Ids from HN Api
⌨️ (0:17:14) Starting work on App.js
⌨️ (0:22:30) Adding useEffect to App.js to show all story Ids
⌨️ (0:30:00) Explaining how useEffect works
⌨️ (0:36:00) Creating our StoriesContainer.js container/component
⌨️ (0:37:50) Adding the ability to get stories from HN Api
⌨️ (0:39:50) Demonstrating the results that we receive from the HN Api
⌨️ (0:41:30) Creating our Story.js component file
⌨️ (0:43:15) Adding our Story component to the StoriesContainer component
⌨️ (0:44:10) Adding storyId as a prop to the Story.js component
⌨️ (0:46:40) Adding state to our Story.js component
⌨️ (0:47:10) Using useEffect to get a story in our Story.js component
⌨️ (0:47:40) Adding validation when getting stories
⌨️ (0:49:00) Dumping our stories onto the page
⌨️ (0:49:55) Building out the Story.js component with real data
⌨️ (0:53:20) Adding a selector for the story fields
⌨️ (0:56:00) Adding styled components
⌨️ (0:57:00) Building out our StoryStyles.js file using styled components
⌨️ (0:59:00) Adding a title to StoriesContainer.js
⌨️ (1:00:00) Adding a StoryWrapper to our Story.js component
⌨️ (1:01:50) More work on styling
⌨️ (1:02:30) Adding styling for StoryMeta
⌨️ (1:03:55) Adding styling for StoryMetaElements & styled component props
⌨️ (1:04:55) Adding our styled components to our Story.js component
⌨️ (1:11:30) Adding StoriesContainerStyles for more styling on the container
⌨️ (1:12:05) Looking at adding global styles (createGlobalStyle)
⌨️ (1:13:00) Adding our container styles to StoriesContainer.js
⌨️ (1:14:55) Brief look at the React profiler
⌨️ (1:16:00) Quick run through as to what we have built so far
⌨️ (1:18:10) Making our time display properly using mapTime.js
⌨️ (1:22:00) Adding InfiniteScroll to our application (custom hook)
⌨️ (1:22:40) Constants to be used by InfiniteScroll for per page items
⌨️ (1:39:05) Adding debounce functionality for scrolling
⌨️ (1:42:00) Adding a fixture folder with fixtures for tests
⌨️ (1:46:00) Testing! Lets test App.js
⌨️ (1:48:00) Adding react-testing-library to our application
⌨️ (1:59:00) Adding Jest coverage (good practise to do so)
⌨️ (2:02:00) Testing the StoriesContainer.js
⌨️ (2:03:40) Testing the Story.js component
⌨️ (2:10:00) Testing the HnApi.js file
⌨️ (2:22:18) Looking at our coverage and more testing!
⌨️ (2:22:53) Collecting coverage from the right places
⌨️ (2:25:43) Looking at React memo
⌨️ (2:27:33) Adding memo to Story.js to prevent additional Api calls
⌨️ (2:29:18) Overview of what we have achieved!
⌨️ (2:30:29) Running our application through Lighthouse!
⌨️ (2:33:00) Thanks for watching, I hope you learned a lot!