Open In App

Explain new Context API in React

Improve
Improve
Like Article
Like
Save
Share
Report

In this article we will discuss about the context API in React and its uses with implementation.

What is Context API?

Context API is used to pass global variables anywhere in the code. It helps when there is a need for sharing state between a lot of nested components. It is light in weight and easier to use, to create a context just need to call React.createContext(). No need to install other dependencies or third-party libraries like redux for state management.

Why is context API used?

Context API solves the problem of prop drilling in React. Prop Drilling occurs when data is to be passed between multiple layers before finally sending it to the required component. This makes the application slower. This problem is solved by Context API as it creates global variables to be used throughout the application without any middle components involved.It is also easier to use than React Redux

Working of Context API

To work with Context API we need React.createContext. It has two properties Provider and Consumer. The Provider acts as a parent it passes the state to its children whereas the Consumer uses the state that has been passed.

Benefits of Context API over React Redux

  • In Redux we have to manipulate or update multiple files to add even a single feature but in Context it can be done in much lesser lines of code
  • One way data binding in React is maintained using Context whereas Redux violates it.
  • Multiple stores/contexts can be created using Context whereas Redux creates just a single store

Implementing Context API

Creating React Application:

Step 1: Create a React application using the following command.

npx create-react-app project

Step 2: After creating your project folder(i.e. project), move to it by using the following command.

cd project

Step 3: We will create two new files one is Context.js to create our context and another file named as WelcomePage.js to create a component named as welcomePage.

Project Structure: It will look like this.

Project Structure

Apporach: We will showing a page that shows the name and id of the user using Context API. In the src folder create a file as Context.js, in the file create context here we are naming it as UserContext. The context comes up with properties consumer and provider, so we are keeping it in const Provider and Consumer. In the file .js, we are creating a simple Component that shows simple message with the name and id that we will pass through the provider that we are creating next in index.js We wrap the App component within Provider and also pass value if we don’t provide any value, in this case, it will show a blank page, here we are passing the name and id to the value.

Example: Write the following code in respective files

  • Context.js: We create the consumer and provider in this file
  • WelocomePage.js: The consumer consumes the value in this file
  • Index.js: The provider is given to the application in this file
  • App.js: The components are imported in this file and then rendered on the webpage

Javascript




// Context.js
import React from 'react';
  
const UserContext =React.createContext();
  
export const Provider = UserContext.Provider;
export const Consumer = UserContext.Consumer;


Javascript




// WelcomePage.js
  
import React from "react";
import { Consumer } from "./Context";
  
const WelcomePage = () => {
    return (
        <div>
            <h1>Welcome User :</h1>
            <Consumer>
                {(value) => (
                    <h2>
                        Name: {value.name} id :{value.id}{" "}
                    </h2>
                )}
                //this function takes the value as prop
            </Consumer>
        </div>
    );
};
  
export default WelcomePage;


Javascript




// index.js
  
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App'
import {Provider} from './Context'
  
ReactDOM.render(
  <Provider value={{name:"Geeksforgeeks", id:195}}>
    <App />
  </Provider>,
  document.getElementById('root')
);


Javascript




// App.js
  
import WelcomePage from "./WelcomePage";
  
function App() {
  return (
    <div className="App">
       <WelcomePage/>
    </div>
  );
}
  
export default App;


Step to Run Application: Run the application using the following command from the root directory of the project.

npm start

Output:



Last Updated : 07 Aug, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads