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
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
Top comments (3)
I just learned about it too. but what are the cases where you would choose this over something like redux.
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.
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.