Start Working with React Context API

    Jul 27, 2021       by Pankaj Kumar
react-context-api.jpg

There are different ways by which data can be shared between multiple components kept at different level in ReactJS.Below are the common ways by which data can be shared :

  1. Using props
  2. Using Redux
  3. Using Context API

 Redux is one of the most popular way which accomplish this task. But apart from Redux we also have Context API which can do the same task for us is little bit easy manner.

Context API provides the way to pass data from parent component to deep nested child component without passing the data at each level of component. In the small level of application data is communicated between parent to child using props, Which is not suitable if we are working with huge application and dealing with a large number of Components.

React Context API

This is used to provide state across entire , or some part of the application.We will discuss futher this is achieved using createCotext function to define the context. A provider component is mainly a component which wraps the component tree which will access the context value. After Passing the value from the top level the next task is to consume the context at the required nested component. Then either a Consumer component, Context class member or useContext is used to access the state value.

1. Creating a Context

While working with Context API, At the begining we need to create the context using below syntax:

const PostContext = React.createContext(defaultValue);

 

Above command create a Context object. Above function takes a parameter which is the default implementation and returns an object containing Provider and Consumer members that can be used to provide context to components and access that context from any nested level component. Whenever React renders the component that subscribe the Context object, Closest mathing provider in the tree will be read.  

 

2. Providing Context

After creating the Context object, next part is to provide that context, Syntax is:

<PostContext.Provider value={/* some value */}>

 

Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes. It mainly accepts the value prop to be passed to the consuming components that are the descendants of this Provider. One Provider can be connected to the many consumers. Providers can be nested to override the values deeper within a tree. As we have overridden the default value of the className and we get the latest value of the className in the component tree.

 

3. Consuming Context

<PostContext.Consumer>

{value => /* render something based on the context value */}

</PostContext.Consumer>

 

This is the component which consumes the context value. It receives the latest context value and returns the React node. The value argument passed to a function will be equal to a value prop of the closest Provider for this context above in the tree. If there are no Providers for the context above, the value argument will be equal to the defaultValue that was passed to createContext().

 

 

Let's Get Started Step by Step

 Create a new React Application

Create a new reactjs application using create-react-app tool

npx create-react-app react-context-app

 

When the installation completes then navigate to the the created project folder using cd react-context-app. In this demo application we will mainly pass the post data from parent component to the nested Component. So parent Component would be App component, Inside it we will have a posts component and inside posts component we will have a postItem component. So basically we will pass the data from App component to postItem component which is second level child component.

Create Context

Now first thing we need to do is create context in the App.js file using below code:

export const PostContext = React.createContext({});

 

So now our App.js file will look like below:

 

 
import React from 'react';
import './App.css';
import Posts from './post/posts.js';
 
export const PostContext = React.createContext({});
 
const App = () => {
 
  const post = {
    title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
    avatar: "https://i.picsum.photos/id/326/200/300.jpg?hmac=SKzjQ5ycCVyISiOfq2m-GqpQ5zWT_J202KPYG7z0uB4",
    likes: 51,
    description: `uia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto`,
    link:"https://jsonplaceholder.typicode.com/posts",
  
  }
  return (
    <div className="App">
      <PostContext.Provider value={post}>
        <Posts />
      </PostContext.Provider>
    </div>
  );
}
 
export default App;
 

 

Now the value is passes from the top/parent level component and our next task is to consume that context value in the nested component.

Next component we are having is Posts component, Here we are not going to do anything to pass data to child component. Let's have a look at the code inside this file.

 

 
import PostItem from './postItem';
 
const Posts = ()=> {
    return (
        <PostItem />
    )
}
 
export default Posts;
 

 

In the above component we have not done anything to pass the context value to the child component,

Now let's consume the context value in the postItem component. Let' have a look at the code inside postItem component.

 

 
import { PostContext } from '../App.js'
const PostItem = () => {
    return (
        <PostContext.Consumer>
        {(post)=> {
            return (                        
                <div style = {{'marginTop':'20px'}} className="container">
                    <div className="avatar-flip">
                        <img src={post.avatar} height="150" width="150" alt="" />
                    </div>
                    <h2>{post.title}</h2>
                    <p>{post.description}</p>
                    <h3>{post.likes}</h3>
                    <h4><a href={post.link} target="_blank" rel="noopener noreferrer">Post Social Link</a></h4>
                </div>
            )
        }}
    </PostContext.Consumer>
    )
}
export default PostItem;
 

 

Now we are done with the task now run the application and navigate to the browser. You will see the post data rendered over the page.

 

Find complete source code over GitHub

 

Conclusion

Context is very easy to use in comparison to Redux library. I hope you understand all about the Context API.

That’s all for now. Thank you for reading and I hope this post will be very helpful  to start work with React Context API.

Let me know your thoughts over email pankaj.itdeveloper@gmail.com. I would love to hear them and If you like this article, share it with your friends.

Thank You!


WHAT'S NEW

Find other similar Articles here: