Context API in ReactJS

ReactJSWeb DevelopmentFront End Technology

In this article, we are going to see how to access the data without passing it through every parent component in the class-based component.

Context APIs are used to set the global data and this data can now be accessed in any of the children's components without the need to pass it through every parent component.

Example

Suppose there are three components namely, A, B and C. A is the parent component of B and B is the parent component of C. So, our component structure is as follows − A→B→C.

We have defined some data in A and want to handle it in component C. So there are two approaches to handle this −

  • Either pass this data through B and to C which is not a preferred way.

  • Another way is to use Context API which is used to handle the data centrally which can be accessed by any component without passing it to every parent component.

In this example, we are going to build an authentication React application which logs in or logs out users in the children component and updates the state accordingly.

We will build an App Component which has two LogIn and LogOut Components which access the state provided by the Context Provider and updates it accordingly.

AuthContext.js

import React from 'react';

const authContext = React.createContext({
   auth: null,
   login: () => {},
   logout: () => {},
});

export default authContext;

App.jsx

import React, { useState } from 'react';
import LogIn from './Login';
import LogOut from './Logout';
import AuthContext from './AuthContext';

const App = () => {

   const [auth, setAuth] = useState(false);
   const login = () => {
      setAuth(true);
   };
   const logout = () => {
      setAuth(false);
   };
   return (
      <React.Fragment>
      <AuthContext.Provider
      value={{ auth: auth, login: login, logout: logout }}
      <p>{auth ? 'Hi! You are Logged In' : 'Oope! Kindly Login'}
      <LogIn />
      <LogOut />
      </AuthContext.Provider>
      </React.Fragment>
   );
};
export default App;

Login.js

import React, { Component } from 'react';
import AuthContext from './AuthContext';

class Login extends Component {
   static contextType = AuthContext;
   render() {
      return (
      <div>
      <button onClick={this.context.login}>Login</button>
      </div>
      );
   }
}
export default Login;

Logout.js

import React, { Component } from 'react';
import AuthContext from './AuthContext';

class Logout extends Component {
   static contextType = AuthContext;
   render() {
      return (
      <div>
      <button onClick={this.context.logout}>Logout</button>
      </div>
      );
   }
}

export default Logout;

Output

This will produce the following result.

raja
Published on 18-Mar-2021 10:30:18
Advertisements