Open In App

Explain new Context API in React

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

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.

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
import React from 'react';
  
const UserContext =React.createContext();
  
export const Provider = UserContext.Provider;
export const Consumer = UserContext.Consumer;




// 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;




// 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')
);




// 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:


Article Tags :