HOW TO JAVASCRIPT

How to use Context API in ReactJS

how-to-use-context-api-in-reactjs
Written by encodedBicoding

Hey, how is your learning coming so far on this blog? today, we are going to learn how to use context API in ReactJS. You can recommend this blog to friends and family in the tech space, you can also share articles on this blog to your network. I need your support to reach more people. Check out how to build a website using HTML and CSS if you are still new to programming and you just magically found your way here.

Here’s a beautiful scenario, you have made a beautiful website, with data being exchanged all around, But as the website grows, the data becomes harder to maintain. You need to manage state off the bat, without having to install anything… Say hello to Context API! You are going to learn how to use context API in ReactJS today! 😀

Before we learn how to use Context API in ReactJS, let us first know what is context API… Enjoy!

What is Context API?

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Since release 16.3, React has had a stable version of Context API  that can be used to easily share data across multiple components. It can be passed directly to the components that need it, thus preventing props drilling.

Check out the documentation on Context API

Why use Context API?

Context is mainly used when you want simple state management. Context makes you avoid props drilling. In Context, you make the parent component a provider and define the child as a consumer that directly uses props from the parent rather than the passing of props through each child component that leads up to the component where it is needed.

How to use context API – A basic example

First, create a new project with create-react-app.

npx create-react-app react-context-app

When the project is ready, we have to create a few files.

src/context/main.js
src/component/main.js
React Context is initialized with React.createContext top-level API


import React, { createContext } from 'react';

const AppContext = createContext();

`createContext` is used to initialize the React Context. It creates the context object with the Provider and Consumer component. It takes in a default value which can only be used when a component does not have a matching Provider above its tree

– Providing the value of the context to the application

consuming the value

In your `App.js` add the Provider to the app by wrapping it around the `AppComponent`

 

Any Questions? Please use the comment section

Appreciation

Credits: Odunayo Okebunmi, Software Engineer

About the author

encodedBicoding

Software Engineer || Tech Enthusiast.
Ex @andela
Github: https://github.com/encodedBicoding
Geek Name: EncodedBicoding
Real Name: Dominic Isioma Olije

Leave a Comment