Skip to main content
react-context-api

React’s New Context API With Example

This tutorial help to understand React Context API With Example. The react provides Context API to pass parameters and data across the component without props.

The new context API was introduced with version 16.3. The React Context APIs are quite useful for managing states without having to delve into components for props. In other languages, this is referred to as a global variable.

Why Do we use Context API

React generally passes data from one component to another via props from the top down (parent to child), but this can be time-consuming if some data is required to be passed across react components, such as the current authorized user, theme, or localization information. If data is requested by some components within the application, props can be used.

Checkout Other tutorials:

Simple React Context API With Example

Let’s make a react project to get a better understanding of how the context API works. Open a command prompt and type the following command –

npx create-react-app context-api-example
cd context-api-example

start the react application –

npm start

Create React Context API Object

Let’s create context-api object in the file app.js. The React.createContext() method is used to create an object and returns the Context object.

import { createContext } from 'react';
const {Provider, Consumer } = React.createContext();

We’ll now make the wrapper component, which will return the Provider component. All the items from which you want to access the context will be added as children. The code below will be added to the file app.js

class ProviderComponent extends Component {
    state = {
        username : "adam",
    }
render() {
        return ( 
        
        )
    }
}

Let’s get started using the Navbar component :

const Navbar = () => (

<div>
    <loggedincontainer>
  </loggedincontainer></div>

)

We’ll now pass username info from the provider component to the Navbar component. Using the context API, we can get information about the state of the provider component.

const LoggedInContainer = () => (

<div>
     <a href="#" class="dropdown-toggle" data-toggle="dropdown">Welcome, {(context) => context.username} <b class="caret"></b></a>
</div>

)

Conclusion

We’ve made a basic react application that consumes the state of the provider component using context rather than prop drilling. It assists in the creation of global variables that are required by many application components. For more complicated applications, you can use redux.

Leave a Reply

Your email address will not be published. Required fields are marked *