React.js useContext Hook Login User and Storing it Example Tutorial For Beginners 2020

You are currently viewing React.js useContext Hook Login User and Storing it Example Tutorial For Beginners 2020

 

Welcome folks today in this blog post we will be looking at a react.js useContext Hook example from scratch. All the source code is given below. A step by step youtube video is also shown below.

 

 

 

 

 

 

Get Started

 

 

In order to get started you need to install this dependency

 

npm i react-router-dom

 

Now we want to install this dependency in order to get started with the router

 

So now inside your app.js file you will create your app component with the routing functionality added like below

 

 

 

 

So now inside this block of code we have two components Index and About components which are listed in the Routing parameters. Now we need to create this components

 

pages/index.js

 

 

 

pages/about.js

 

 

 

Now you need to create a UserContext.js file inside your root directory of your project

 

 

 

Here we have used the createContext method of react to create a context which has default value of null

 

Now we need to include this file UserContext.js file inside our app.js file like this

 

 

 

Now here in this block of code we have wrapped whole router tag inside the UserContext.Provider tag and also we have added a attribute value here you can pass any sort of data such as string, number or object. Here we are passing a string value.

 

Now to receive this value inside index.js file as shown below

 

 

 

 

Now we need to repeat the same thing for about.js file and copy paste the below code

 

 

 

 

 

 

 

 

And now we can make this very interesting by passing instead of a static string we can pass a object to the component like this

 

 

 

 

So inside this block of code in order to pass the objects we have wrapped this inside double curly brackets and we have the user and setUser which is actually a useState hook which we have declared above.

 

Now to receive it inside index and about components we will do something like this

 

 

 

 

 

 

 

 

So now as you can see we have a current user gautam inside the userContext  and also we have a button to change that user to John and when we click it after this when we open the about page it will stay at the about page also. This is the magic of useContext Hooks in React.

 

Now to implement Login functionality inside react app we will make a simple utility class called as Login.js inside utils folder like this

 

utils/Login.js

 

 

 

We have a single user we are exporting we have three properties inside this object of user which is id,username and email of the user

 

Now we need to include this  Login.js file inside your components index and about like this

 

 

 

 

 

 

 

 

Leave a Reply