DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Sai gowtham
Sai gowtham

Posted on • Updated on

How to Use New React Context API Detailed

context api

React Context API is available in the react16.3 so let's build a counter using
Context API.

Context API helps us to pass down the data to the components without the use of props at every component.

In our counter app, we only pass down one level.So let's install a react app using create-react-app

npm install -g create-react-app
create-react-app newContext
cd newContext
npm start  //to start dev server
Enter fullscreen mode Exit fullscreen mode

Now open with your code editor.

Let us create a new file context.js add these below code.

In above code First, we imported React from its library.

on line 7 we created a context using the createContext method and passed initial state.

In Below code first, we are using props to pass the value.

Now we are replacing it with context API Instead of using props in the Counter component.

First, we need to import NumberContext from our context.js file

In line 39 above code tells first we are providing value to our component by wrapping our Counter component with the NumberContext.Provider.

Now, we can use it in our Counter component by using Consumer wrapper.

That's all in react documentation says Context is designed to share data that can be considered β€œglobal” for a tree of React components.

Code repository

Checkout --> Best laptops for programming students

Top comments (3)

Collapse
 
jay97 profile image
Jamal Al

I just learned about it too. but what are the cases where you would choose this over something like redux.

Collapse
 
ghanshyamkdobariya profile image
Ghanshyam

Before you jump to react context - know what it prop drilling problem from kent c dodds
blog.kentcdodds.com/prop-drilling-...

you can choose context approach when your screens in SPA are less and you have small amount of data to handle in entire app.

Collapse
 
sait profile image
Sai gowtham Author

Redux is a seperate Library used to manage the state in react. React context is used in particular use cases like login and logout or using different themes in your app.

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.