React Context API is available in the react16.3 so let's build a counter using
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
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.
Checkout --> Best laptops for programming students