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

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

 

 

import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import { Index } from "./pages";
import { About } from "./pages/about";

export default function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about/">About</Link>
            </li>
          </ul>
        </nav>
        <Route path="/" exact component={Index} />
        <Route path="/about/" component={About} />
      </div>
    </Router>
  );
}

 

 

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

 

import React from "react";


export function Index() {

  return (
    <div>
      <h2>Home</h2>

    </div>
  );
}

 

 

pages/about.js

 

import React from "react";


export function About() {

  return (
    <div>
      <h2>About</h2>

    </div>
  );
}

 

 

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

 

import { createContext } from "react";

export const UserContext = createContext(null);

 

 

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

 

import {UserContext} from './UserContext'

export default function App() {

  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about/">About</Link>
            </li>
          </ul>
        </nav>
        <UserContext.Provider value="hello world this is gautam">
          <Route path="/" exact component={Index} />
          <Route path="/about/" component={About} />
        </UserContext.Provider>
        
      </div>
    </Router>
  );
}

 

See also  Node.js Library to Export React.js Class & Functional Component to PNG,JPEG Image & PDF Document and Download it as Attachment in Browser Using Javascript Full Project For Beginners

 

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

 

 

import React, { useContext } from "react";
import { UserContext } from "../UserContext";

export function Index() {
  const msg = useContext(UserContext);

  return (
    <div>
      <h2>Home</h2>
      {msg}
    </div>
  );
}

 

 

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

 

 

import React, { useContext } from "react";
import { UserContext } from "../UserContext";

export function About() {
  const msg = useContext(UserContext);

  return (
    <div>
      <h2>About</h2>
      {msg}
    </div>
  );
}

 

 

 

 

 

 

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

 

 

export default function App() {
  const [user, setUser] = useState("gautam");



  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about/">About</Link>
            </li>
          </ul>
        </nav>
        <UserContext.Provider value={{user,setUser}}>
          <Route path="/" exact component={Index} />
          <Route path="/about/" component={About} />
          </UserContext.Provider>
        
      </div>
    </Router>
  );
}

 

 

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

 

import React, { useContext } from "react";
import { UserContext } from "../UserContext";

export function Index() {
  const {user,setUser} = useContext(UserContext);

  return (
    <div>
      <h2>Home</h2>
      {user}
      <button onClick={() => setUser("John")}>Change User</button>
    </div>
  );
}

 

See also  React.js Node.js Tutorial to Display Country Flag Emoji in Browser Using tiny-flag-react Library in Javascript Full Project For Beginners

 

import React, { useContext } from "react";
import { UserContext } from "../UserContext";

export function About() {
  const {user} = useContext(UserContext);

  return (
    <div>
      <h2>About</h2>
      {user}
    </div>
  );
}

 

 

 

 

 

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

 

export const login = async () => {
  return {
    id: 4,
    username: "bob",
    email: "bob@bob.com"
  };
};

 

 

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

 

 

import React, { useContext } from "react";
import { UserContext } from "../UserContext";
import { login } from "../utils/login";

export function Index() {
  const { user, setUser } = useContext(UserContext);

  return (
    <div>
      <h2>Home</h2>
      <pre>{JSON.stringify(user, null, 2)}</pre>
      {user ? (
        <button
          onClick={() => {
            // call logout
            setUser(null);
          }}
        >
          logout
        </button>
      ) : (
        <button
          onClick={async () => {
            const user = await login();
            setUser(user);
          }}
        >
          login
        </button>
      )}
    </div>
  );
}

 

 

import React, { useContext } from "react";
import { UserContext } from "../UserContext";


export function About() {
  const { user } = useContext(UserContext);

  return (
    <div>
      <h2>About</h2>
      <pre>{JSON.stringify(user, null, 2)}</pre>
    </div>
  );
}

 

 

 

 

Leave a Reply