Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Programming

    Инструменты JavaScript / Node.js разработчика

    Programming

    23. Node.js Lessons. Domains, asynchronous try.. catch. Part 2.

    Job

    Front-End Developer Job Description | Write a Good Job Post That Will Actually Attract Candidates

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Friday, September 12
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / React / React User Login Authentication using useContext and useReducer.
    JavaScript

    React User Login Authentication using useContext and useReducer.

    Adaware OgheneroBy Adaware OgheneroSeptember 4, 2020Updated:May 26, 2024No Comments24 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    React User Login Authentication using useContext and useReducer.
    React User Login Authentication using useContext and useReducer.
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    React User Login Authentication using useContext and useReducer.
    React User Login Authentication using useContext and useReducer.

    Introduction

    Authentication is one of the parts you might have to deal with when building frontend applications. Usually, this involves using a token generated by the server to authenticate the request to the server and also secure protected the frontend(pages that require a user to be signed in).

    Due to the fact that you might be using this token and other data in multiple components in the frontend of your application to make requests to the server, it is important that we should be able to share this token across components that need it.

    Usecontext

    Use context is a hook that allows us pass data to multiple components without prop drilling. UseContext allows us read the current value from a context object and triggers a serenader when the context provider value has changed. You can read more in the docs

    This is a simple example to pass a dark theme down multiple components.

    //Context.js
    
    import React from 'react';
     
    export const AppThemeContext = React.createContext('dark');

    To use react context you have first create a context object, we do that using the `React.createContext` then we pass the value for the context object we created.

    After creating the context object a context provider component is used to wrap all the components that need access to that context object, this means that only components under the context provider tree can get access to the theme value.

    //ParentComponent.js
    
    import {ThemeContext} from './Context';
     
    const ParentComponent = () => (
      <ThemeContext.Provider value="dark-mode">
        <Dashboard />
        <Login />
        <Setting/>
      </ThemeContext.Provider>
    );

    Now we have the value of the Themecontext provider available to all its child components (Dashboard, Login and Setting) all we have to do is read that value from the context object using useContext Hook in the component that needs the theme value.

    // Dashboard.js
    
    import React,{useContext} from 'react';
    import {ThemeContext} from './Context';
     
    const DashBoard = () => {
      const themeMode = useContext(ThemeContext); //dark
     
      return (
        <div className={themeMode}>
          ......
        </div>
      );
    };

    When we pass the context object(ThemeContext) as an argument to the useContext hooks and it gives us the current value in the Context object if the context value of the `ThemeContext.Provider` changes any component that calls the useContext will be rerendered with the latest value in the context provider.

    Note that you can pass other objects, arrays e.t.c as the value in the context object(ThemeContext.Provider) it is not limited to only strings.

    UseReducer

    Usereducer is a bit similar to Usestate hooks but it uses the state reducer pattern to update/change state. The useReducer hook accepts a reducer of type `(state, action) => newState` and returns the current state and a `dispatch` function that you can use to trigger state changes.

    //useReducer Example
    
    const initialState = {count=0}

function reducer(state,action)
        switch (action.type) {
        	case 'increment':
          		return {count: state.count + 1};
       	case 'decrement':
          		return {count: state.count - 1};
       	default:
          		throw new Error();
    }
    
    function Counter() {
      const [state, dispatch] = useReducer(reducer, initialState);
      return (
        <>
          Count: {state.count}
          <button onClick={() => dispatch({type: 'decrement'})}>-</button>
          <button onClick={() => dispatch({type: 'increment'})}>+</button>
        </>
      );
    }
    

    The above example is from the React docs

    If you have used redux in the past you will be familiar with this. What happens here is that we pass the useReducer function two arguments a reducer and an initial state,  when we want to update the state we call the dispatch method with type property that specifics the type of state changes we want to affect.

    In the example when you increment the counter, the dispatch method is passed an object with a `type` property which the reducer will use to calculate a new state `count: state.count + 1`.

    useReducer gives us a way to track what changes state and how state changes.

    Now that we have a basic idea of how useContext and useReducer works lets see how we can combine both of them in handling login authentication in React applications.

    Walkthrough

    We will be building a login authentication using useReducer to manage state and React context to share this state across multiple components. The idea is that we will have a login page with two input fields for username and password that we authenticated on submit. If the login details are valid they are routed to the dashboard page which is a protected route then you can navigate to other protected routes and perform actions restricted to authenticated users.

    Before we dive deep into the tutorial, let’s try to understand how the different components will fit together in order to build this application.

    Folder Structure

    This is what the final project structure should look like:

    //Final folder structure
    
    ├── .gitignore
    ├── README.md
    ├── package.json
    ├── public   
    ├── src
    │   ├── App.css
    │   ├── App.js
    │   ├── App.test.js
    │   ├── Components
    │   │   └── AppRoute.js
    │   ├── Config
    │   │   └── routes.js
    │   ├── Context
    │   │   ├── actions.js
    │   │   ├── context.js
    │   │   ├── index.js
    │   │   └── reducer.js
    │   ├── Pages
    │   │   ├── Dashboard
    │   │   │   ├── dashboard.module.css
    │   │   │   └── index.js
    │   │   ├── Login
    │   │   │   ├── index.js
    │   │   │   └── login.module.css
    │   │   └── NotFound
    │   │       ├── index.js
    │   │       └── notfound.module.css
    │   ├── index.css
    │   ├── index.js
    │   ├── logo.svg
    │   ├── serviceWorker.js
    │   └── setupTests.js
    └── yarn.lock

    We have a components folder which contains all the reusable components we use in this tutorial.

    • AppRoute: This is a component used to define protected routes(routes that can only be accessed by authenticated users)

    Then we will have a context folder where all the context related files are, we have

    • actions.js: I used a redux motivated file structure, this file contains and exports async functions that need to dispatch state changes to the reducer.
    • context.js: This file is where we initialize the different context objects we will be needing and some custom hooks that compose logic.
    • reducer.js: This file contains the reducer that we will use to manage the authentication state.
    • Index.js: The file simply exports the contents of the three files above

    We have a Config file where our route config and any other config files are:

    • routes.js: This file will contain config for the different routes in our application

    Finally, we have two pages we mean we will be using a routing library(react-router) to route between these pages.

    • Login page
    • Dashboard page

    This is most of the components that will be used in this tutorial, now we can dive in setting up and writing code.

    Scaffold Application

    Enter any directory on your PC or where you keep your pet projects, then in your terminal run the command below to bootstrap a new react application using create-react-app

    npx create-react-app login-auth
    cd login-auth

    This uses the create-react-app to create a simple react application inside a directory named login-auth with the basic dependencies installed:

    Install dependencies.

    We will need a routing library because will need to handle routing between different pages. I decided to go with react-router for this project, to install it run:

    npm install react-router-dom
    
    or
    
    yarn add react-router-dom

    Create folders

    Before we can dive into the code lets create the folders that will house the different parts of our application. We will set up the folders for our configs, components, context(for react context related code), and pages(pages for the different routes).

    Ensure you are in the projects root directory then run this in terminal to change into the `src` directory:

    cd src

    In the src folder create the following folders:

    • Components
    • Context
    • Pages
    • Config

    Setup Routing(React Router)

    We installed react-router as one of our dependencies because we need to handling routing between pages in our application. In the Config folder create a file called `routes.js` , in this file we will define all the routes we want to have in this application.

    In the `routes.js`  file add the following code:

    // Config/routes.js
    
    import React from "react";
    import Login from '../Pages/Login'
    import Dashboard from '../Pages/Dashboard'
    import PageNotFound from '../Pages/PageNotFound'

    This is all the page components we will be using in our application. We will create these components later in this article, it is not magic don’t worry.

    Now let’s define the different routes for our application, In the same file (routes.js) we create an array of objects that define what path is mapped to what `component`:

    // Config/routes.js
    
    const routes =[
      {
        path:'/',
        component: Login
      },
      {
        path:'/dashboard',
        component: Dashboard
      },
      {
        path:'/*',
        component: PageNotFound
      },
    ]
    
    export default routes

    Now lets setup react-router in the `App.js` file, it can be found in the application’s root directory.

    // App.js
    
    import React from 'react';
    import {
      BrowserRouter as Router,
      Redirect,
      Route,
      Switch,
    } from 'react-router-dom';
    import routes from './Config/routes.js';
    
    function App() {
      return (
        <Router>
          <Switch>
            {routes.map((route) => (
              <Route
                key={route.path}
                path={route.path}
                component={route.component}
              />
            ))}
          </Switch>
        </Router>
      );
    }
    
    export default App;

    What happens here is that we loop through the routes we defined in the routes.js in the react-router `Switch` component in order to set up routing in our application.

    Create Page Components

    In the `Page` Folder lets create a `Login` Folder which will house all the login page related files, in this folder create two files an `index.js` and `login.module.css`

    In the index.js file add the following:

    // Pages/Login/index.js
    
    import React from 'react';
    
    import styles from './login.module.css';
    
    function Login(props) {
      return (
        <div className={styles.container}>
          <div className={styles.formContainer}>
            <h1>Login Page</h1>
    
            <form>
              <div className={styles.loginForm}>
                <div className={styles.loginFormItem}>
                  <label htmlFor='email'>Username</label>
                  <input type='text' id='email' />
                </div>
                <div className={styles.loginFormItem}>
                  <label htmlFor='password'>Password</label>
                  <input type='password' id='password' />
                </div>
              </div>
              <button>login</button>
            </form>
          </div>
        </div>
      );
    }
    
    export default Login;
    

    This is the HTML for the login page so now let’s add the styles for this page in the `login.module.css` file.

    /* Pages/Login/login.module.css */
    
    .container {
      min-height: 100vh;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .formContainer {
      width: 200px;
    }
    .error {
      font-size: 0.8rem;
      color: #bb0000;
    }
    
    .loginForm {
      display: flex;
      flex-direction: column;
    }
    
    .loginFormItem {
      display: flex;
      flex-direction: column;
      margin-bottom: 10px;
    }
    

    These are the styles for the login page. Next we in the `Pages` Folder we create a Dashboard folder then create two files index.js and dashboard.module.css in that folder.

    Read More:  Fortune 500 top hiring trends in 2019. How big corporations hire top talents?

    In the `index.js` file add the following markup for the dashboard page

    // Pages/Dashboard/index.js
    
    import React from 'react'
    import styles from './Dashboard.module.css'
    
    function Dashboard(props) {
       
        return (
            <div style={{ padding: 10 }}>
                <div className={styles.dashboardPage} >
                    <h1>
                        Dashboard
                    </h1>
                    <button className={styles.logoutBtn} >Logout</button>
                </div>
                <p>Welcome to the dashboard</p>
            </div>
        )
    }
    
    export default Dashboard

    Then we can add the styles for the dashboard page to the `dashboard.module.css` file:

    /* Pages/Dashboard/dashboard.module.css */
    
    .logoutBtn {
      height: '30px';
      width: '100px';
    }
    
    .dashboardPage {
      display: flex;
      width: 100%;
      justify-content: space-between;
    }

    Finally, we create the component for the NotFound page, this is a page that shows when a user tries to access a route that is not defined in out routes config. Similar to the other page we have created, we can go ahead and create a `NotFound` folder then inside it we create an `index.js` and a `notfound.module.css` file.

    In the `index.js` file add the following code:

    // Pages/NotFound/index.js
    
    import React from 'react';
    import styles from './notfound.module.css';
    
    function NotFound(props) {
    	return (
    		<div className={styles.container}>
    			<h1>Page not found</h1>
    		</div>
    	);
    }
    
    export default NotFound;
    

    Then we can add the styles for that page to the `notfound.module.css`:

    /* Pages/NotFound/notfound.module.css */
    
    .container {
    	min-height: 100vh;
    	width: 100%;
    	display: flex;
    	justify-content: center;
    	align-items: center;
    }
    

    We have successfully created all the pages and set up our router, now we should be able to view these different pages and navigate between pages.

    Run the below code in the project root to start the application:

    Yarn start 


        or
    

Npm start

    Our application should start then we can view the Login page in the http://localhost:3000/login route and the Dashboard Page in http://localhost:3000/dashboard 
route.

    Setup Context for Authentication

    We will start by creating the context objects we will be using in our application, we will create two context object:

    • AuthStateContext: This context object will contain the authentication token and user details.
    • AuthDispatchContext: We will use this context object to pass the dispatch method given to us by the `useReducer` that we will be creating later to manage the state. This makes it easy to provide the dispatch method to components that need it.

    In the `Context` folder we created earlier, create a file called `context.js`. This file will contain the context objects and everything we need to use the context object.

    To create the context objects we add the below to the `context.js` file:

    // Context/context.js
    
    import React from "react";
    
    const AuthStateContext = React.createContext();
    const AuthDispatchContext = React.createContext();

    Next, we will want to create custom hooks that will help us read values from these context objects without having to call React.useContext in every component that needs that context value and it also does some error handling in case these contexts are used outside the context providers.

    In the same file (context.js) we create a `useAuthDispatch` hook and a `useAuthDispatch` :

    // Context/context.js
    
    [...]
    
    export function useAuthState() {
      const context = React.useContext(AuthStateContext);
      if (context === undefined) {
        throw new Error("useAuthState must be used within a AuthProvider");
      }
    
      return context;
    }
    
    export function useAuthDispatch() {
      const context = React.useContext(AuthDispatchContext);
      if (context === undefined) {
        throw new Error("useAuthDispatch must be used within a AuthProvider");
      }
    
      return context;
    }
    
    
    

    This will be useful later in the article when we start adding state to our components.

    Finally, for the context file we create a custom provider named `AppStateProvider`, This provider composes the logic that helps us manage our application.

    Add the following code to the `context.js` file:

    // Context/context.js
    
    export const AuthProvider = ({ children }) => {
      const [user, dispatch] = useReducer(AuthReducer, initialState);
    
      return (
        <AuthStateContext.Provider value={user}>
          <AuthDispatchContext.Provider value={dispatch}>
            {children}
          </AuthDispatchContext.Provider>
        </AuthStateContext.Provider>
      );
    };
    

    The above function is our own “state management library”, in the AuthProvider function we first create a means of keeping/managing state using `useReducer`. We haven’t created the reducer function and the initial state(initialState) object passed as arguments to the `useReducer` hook yet but we will later in this tutorial.

    The useReducer returns a user object as state and a dispatch method for triggering state updates/changes, then we pass the user object to as `value` `AuthStateContext` provider also we pass the dispatch method as value to the `AuthDispatchContext` provider.
    What this means is that the user object and dispatch method are available to any children of the `AuthProvider` component.

    Now we can go ahead to create the `AuthReducer` and the `initialState` object that was used by the `useReducer` hook. In the `Context` folder create a new file called `reducer.js`.

    In the `reducer.js` file we just created add the following code to create the `AuthReducer` reducer and the `initialState` object:

    // Context/reducer.js
    
    import React, { useReducer } from "react";
    
    let user = localStorage.getItem("currentUser")
      ? JSON.parse(localStorage.getItem("currentUser")).user
      : "";
    let token = localStorage.getItem("currentUser")
      ? JSON.parse(localStorage.getItem("currentUser")).auth_token
      : "";
    
    export const initialState = {
      userDetails: "" || user,
      token: "" || token,
      loading: false,
      errorMessage: null
    };
    
    export const AuthReducer = (initialState, action) => {
      switch (action.type) {
        case "REQUEST_LOGIN":
          return {
            ...initialState,
            loading: true
          };
        case "LOGIN_SUCCESS":
          return {
            ...initialState,
            user: action.payload.user,
            token: action.payload.auth_token,
            loading: false
          };
        case "LOGOUT":
          return {
            ...initialState,
            user: "",
            token: ""
          };
    
        case "LOGIN_ERROR":
          return {
            ...initialState,
            loading: false,
            errorMessage: action.error
          };
    
        default:
          throw new Error(`Unhandled action type: ${action.type}`);
      }
    };
    

    We create the initial state object which has four properties :

    • `userDetails`: userDetails is for storing the user object returned from the server on successfully login. We try to read the userDetails from the localStorage on initialization in other to persist the login state across sessions.
    • `token`: It is for storing the authentication token(JWT) returned from the server, it is also persisted using the browsers local storage.
    • `loading`: it is for storing the loading state of the login form when it is being submitted.
    • `errorMessage`: it is for storing error message returned if the login fails.

    After creating the initial state we create the reducer function that will be used by the `useReducer` state hook. Like I said earlier when explaining reducers, it is a function that accepts an initialState and an action object({type: “ACTION_TYPE”}) as arguments and then returns a new state based on the action type specified.

    Finally, for the context folder, we want to define some async functions that I call actions(similar to actions in redux). These function dispatch multiple state updates as a result of an Http request or side-effect.
we have two of this actions, a `loginUser` and `logout` function, the `loginUser` function will handle asynchronous requests to the server to authenticate a user login details and a `logout` function used to log a user out of an authenticated session.

    I will be defining these functions in an `actions.js` file similar to how it is done in redux where all the asynchronous functions that change/update state are called actions.

    // Context/actions.js
    
    
    const ROOT_URL = 'https://secret-hamlet-03431.herokuapp.com';
    
    export async function loginUser(dispatch, loginPayload) {
      const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(loginPayload),
      };
    
      try {
        dispatch({ type: 'REQUEST_LOGIN' });
        let response = await fetch(`${ROOT_URL}/login`, requestOptions);
        let data = await response.json();
    
        if (data.user) {
          dispatch({ type: 'LOGIN_SUCCESS', payload: data });
          localStorage.setItem('currentUser', JSON.stringify(data));
          return data
        }
    
        dispatch({ type: 'LOGIN_ERROR', error: data.errors[0] });
        return;
      } catch (error) {
        dispatch({ type: 'LOGIN_ERROR', error: error });
      }
    }
    
    export async function logout(dispatch) {
      dispatch({ type: 'LOGOUT' });
      localStorage.removeItem('currentUser');
      localStorage.removeItem('token');
    }

    `loginUser` action(function) is passed a dispatch method and login payload as arguments, Immediately `loginUser` is called we dispatch a state update of type `REQUEST_LOGIN` to trigger a state update of the AuthReducer state, this tells the AuthReducer that the login requests have started.

    Then if the login was successful an action of type `LOGIN_SUCCESS` and payload containing the login response is passed to the AuthReducer to update the state(the user details and auth token).

    Finally, if the login request fails an action of type `LOGIN_ERROR` is dispatched with an error object as payload to the AuthReducer to update the state(error message).

    For the `logout` action(function), it is also passed a dispatch method. Immediately `logout` is called it dispatches an action of type `LOGOUT`, this resets the AuthReducer state to the initial state(remove the token and user details object from state) and then the remove the `currentUser` and `token` from local storage.

    Now we have done all the setup for our context and state management with useReducer, we will create an `index.js` file in the `Context` folder where we export all the contents of the `Context` folder.
    I usually do this so I have cleaner import statements where I need to use these different modules. Add the following code to the `index.js` you just created:

    // Context/index.js
    
    
    import { loginUser, logout } from './actions';
    import { AuthProvider, useAuthDispatch, useAuthState } from './context';
    
    export { AuthProvider, useAuthState, useAuthDispatch, loginUser, logout };

    Integrate Context into our application

    Now we have all we need to manage our authentication state globally, we can now integrate it into our application. First we start by wrapping our application in the custom provider(`AuthProvider`) we created earlier. This ensures that every component in our application has access to the context objects we created earlier.

    Read More:  How And When To Debounce And Throttle In React

    To do this we go to our applications entry point in `App.js`, we import the custom provider(AuthProvider) and wrap it around all our routes as shown below:

    // App.js
    
    import routes from './Config/routes.js';
    import { AuthProvider } from "./Context";
    
    function App() {
      return (
        <AuthProvider>
          <Router>
            <Switch>
              {routes.map((route) => (
                <Route
                  key={route.path}
                  path={route.path}
                  component={route.component}
                />
              ))}
            </Switch>
          </Router>
        </AuthProvider>
      );
    }
    
    export default App;

    Now the context objects are available to all the routes and sub-components in our application, all we need to do now is read this object where it needs it.

    Implement authentication in the Login page component

    In the Logic component we created earlier we want to implement the login authentication logic, that is :

    • Get the values from the login form
    • Submit the login details to the server for authentication
    • Handle failed login attempt
    • Navigate to the dashboard on successful login.

    In the `Login` component we created earlier in `/Pages/Login/index.js`, define state and input handlers for the email and password input fields.

    // Pages/Login/index.js
    
    [...]
    
    function Login(props) {
    
        const [email, setEmail] = useState('')
        const [password, setPassword] = useState('')
    
       
    
        return (
            <div className={styles.container}>
                <div className={{ width: 200 }}>
                    <h1>Login Page</h1>
                   
                    <form >
                        <div className={styles.loginForm}>
                            <div className={styles.loginFormItem}>
                                <label htmlFor="email">Username</label>
                                <input type="text" id='email' value={email} onChange={(e) => setEmail(e.target.value)} />
                            </div>
                            <div className={styles.loginFormItem}>
                                <label htmlFor="password">Password</label>
                                <input type="password" id='password' value={password} onChange={(e) => setPassword(e.target.value)}  />
                            </div>
                        </div>
                        <button>login</button>
                    </form>
                </div>
            </div>
        )
    }
    [...]

    At this point we have the email and password field available in state, we can now create a function to handle submission of this form details to the server. We will call this function `handleLogin` and will be called on click of the `login` button.

    In the Login component we create the handleLogin function:

    // Pages/Login/index.js
    
    function Login(props) {
    
        const [email, setEmail] = useState('')
        const [password, setPassword] = useState('')
    
    
    
    
        const handleLogin = async (e) => {
           e.preventDefault()
        	let payload = {name, email}
            
        	// async request to the server
        }
    
        return (
            [...]
            <button onClick={handleLogin} >login</button>
            [...]

        )
    }

    In the `handleLogin` function we can choose to make this async request(authentication request) in this component that needs it and handle all the state changes in this component but in some cases, you might find yourself duplicate similar logic in multiple components instead of just having one action that encapsulates all that logic.

    So this one of the reasons why we choose to abstract this async logic to a `loginUser` action/function. `loginUser`  accepts the dispatch method and the payload for the login request. This function then makes a request to the server and dispatches the appropriate state change over the request-response cycle.

    The `loginUser` takes a dispatch method so we can use the `useAuthDispatch` hook we created earlier to get the dispatch method from context.

    Our `handleLogin` function should look something like this now:

    // Pages/Login/index.js
    
    […]
    
    import { loginUser, useAuthState, useAuthDispatch } from '../../Context' 
    […]
    
    function Login(props) {
    
        […]
    
        const dispatch = useAuthDispatch() //get the dispatch method from the useDispatch custom hook
      
    
        const handleLogin = async (e) => {
            e.preventDefault()
            let payload = {name, email}
            try {
                let response = await loginUser(dispatch, payload) //loginUser action makes the request and handles all the neccessary state changes
                if (!response.user) return
                props.history.push('/dashboard') //navigate to dashboard on success
            } catch (error) {
                console.log(error)
            }
        }
    
        return (
            <div className={styles.container}>
                <div className={{ width: 200 }}>
                    <h1>Login Page</h1>
                   <form >
                        <div className={styles.loginForm}>
                            <div className={styles.loginFormItem}>
                                <label htmlFor="email">Username</label>
                                <input type="text" id='email' value={email} onChange={(e) => setEmail(e.target.value)} />
                            </div>
                            <div className={styles.loginFormItem}>
                                <label htmlFor="password">Password</label>
                                <input type="password" id='password' value={password} onChange={(e) => setPassword(e.target.value)}  />
                            </div>
                        </div>
                        <button onClick={handleLogin} >login</button>
                    </form>
                </div>
            </div>
        )
    }
    
    export default Login

    To test the login details are email: `nero@admin.com` and password: `admin123`, on successful login we navigate the user to the dashboard page.

    This login page is not complete yet, right now it doesn’t show any error messages or any loading state to tell the user that the form is still being submitted.

    Lucky for us the `loginUser` action already handles the different state updates based on the response of the login request and all we have to do is read the error message and loading state from context. How lucky can we be? Ok so we have another custom hook we created earlier to read the values from the AuthStateContext called useAuthState.

    We can update the Login component to look like this:

    // Pages/Login/index.js
    
    […]
    
    import { loginUser, useAuthState, useAuthDispatch } from '../../Context'
    
    
    function Login(props) {
    
        const [email, setEmail] = useState('')
        const [password, setPassword] = useState('')
    
        const dispatch = useAuthDispatch()
        const { loading, errorMessage } = useAuthState() //read the values of loading and errorMessage from context
    
    
    
    
        const handleLogin = async (e) => {
            e.preventDefault()
    
            try {
                let response = await loginUser(dispatch, { email, password })
                if (!response.user) return
                props.history.push('/dashboard')
            } catch (error) {
                console.log(error)
            }
        }
    
        return (
            <div className={styles.container}>
                <div className={{ width: 200 }}>
                    <h1>Login Page</h1>
                    {
                        errorMessage ? <p className={styles.error}>{errorMessage}</p> : null
                    }
                    <form >
                        <div className={styles.loginForm}>
                            <div className={styles.loginFormItem}>
                                <label htmlFor="email">Username</label>
                                <input type="text" id='email' value={email} onChange={(e) => setEmail(e.target.value)} disabled={loading} />
                            </div>
                            <div className={styles.loginFormItem}>
                                <label htmlFor="password">Password</label>
                                <input type="password" id='password' value={password} onChange={(e) => setPassword(e.target.value)} disabled={loading} />
                            </div>
                        </div>
                        <button onClick={handleLogin} disabled={loading}>login</button>
                    </form>
                </div>
            </div>
        )
    }
    
    export default Login

    We read the `errorMessage` and `loading` states from the `useAuthState` hook, then we display the error message on failed login attempt and we disable the form when the login request is being made.

    Ideally, you will want to create a separate context object for your loading and error states but I kept them together because this is supposed to be a trivial example.

    Implement Logout in Dashboard

    Here we will try to implement the logout functionality in the dashboard and display the user’s name on the dashboard. Similar to the `loginUser` async action, we have a `logout` action that is used to logout a user from the current session and it takes a dispatch method as an argument.

    Also, we can show the email of the current user by just reading the `email` from context using the `useAuthState` hook

    Our `Dashboard` component should look something like this now:

    // Pages/Dashboard/index.js
    
    import React from 'react'
    import { useAuthDispatch, logout, useAuthState } from '../../Context'
    import styles from './dashboard.module.css'
    
    function Dashboard(props) {
        const dispatch = useAuthDispatch() // read dispatch method from context
        const userDetails = useAuthState() //read user details from context
    
    
        const handleLogout = () => {
            logout(dispatch) //call the logout action
            
            props.history.push('/login') //navigate to logout page on logout
        }
        return (
            <div style={{ padding: 10 }}>
                <div style={styles.dashboardPage} >
                    <h1>
                        Dashboard
                    </h1>
                    <button className={styles.logoutBtn} onClick={handleLogout}>Logout</button>
                </div>
                <p>Welcome {userDetails.user.email}</p>
            </div>
        )
    }
    
    export default Dashboard

    We are almost done with this simple login application but there is a problem, despite the facts that we have authentication now, users can still access routes like the dashboard route even when they are not authenticated.

    Protect authenticated routes

    To fix this we need to define private routes(routes that can only be accessed by authenticated users ) and create a higher-order component Route component that renders the appropriate component if the users is authenticated, if not they are redirected to the Login page

    First, in our routes config, we want to add a property `isPrivate` that specifies if a route is private or not. The two private routes in our application are the Dashboard page and the 404 page.

    // Config/routes.js
    
    […]
    const routes = [
      {
        path: '/login',
        component: Login,
        isPrivate: false,
      },
      {
        path: '/dashboard',
        component: Dashboard,
        isPrivate: true,
      },
      {
        path: '/*',
        component: NotFound,
        isPrivate: true,
      },
    ];
    
    
    export default routes;
    

    Next, we create a higher-order component that will help for protected routes. In our Components folder, lets create a file called `AppRoutes.js`.
    Then we can add the following in the AppRoute component

    // Components/AppRoute.js
    
    import React from "react";
    import { Redirect, Route } from "react-router-dom";
    
    import { useAuthState } from '../../Context'
    
    const AppRoutes = ({ component: Component, path, isPrivate, ...rest }) => {
    
        const userDetails = useAuthState()
        return (
            <Route
                path={path}
                render={props =>
                    isPrivate && !Boolean(userDetails.token) ? (
                        <Redirect
                            to={{ pathname: "/login" }}
                        />
                    ) : (
                            <Component {...props} />
                        )
                }
                {...rest}
            />
        )
    }
    
    export default AppRoutes
    

    What this component does is instead of rendering the component by passing a component attribute to react router’s `Route` component , we use the render prop instead, we check if it is a private route per the config and if there is a `token` present in the AuthStateContext to determine what to render to the user.

    Now we can replace the react-router’s Route component we used to set up routing in the `App.js` and replace it with the `AppRoute` higher-order component we just created.

    // //App.js
    
    [...]
    import AppRoute from './Components/AppRoute';
    
    function App() {
      return (
        <AuthProvider>
          <Router>
            <Switch>
              {routes.map((route) => (
                <AppRoute
                  key={route.path}
                  path={route.path}
                  component={route.component}
                  isPrivate={route.isPrivate}
                />
              ))}
            </Switch>
          </Router>
        </AuthProvider>
      );
    }
    
    [...]
    

    This will ensure that only authenticated users have access to the private route.

    Testing out the application

    We are now done!! Now we can go ahead and test the app. In your terminal run:

    yarn start or npm start

    The application should run and you should be able to test the login authentication.

    Code

    You can find the code for the completed version of this tutorial on Github or You can play with it live on Codesandbox

    Conclusion

    I think we have learned how to combine useReducer and `useContext` to handle login authentication. What I would like us to focus on is how we created our own mini-state management library using React context and useReducer because this can be applied anywhere you need to manage/pass state in a React application.

    References

    • https://kentcdodds.com/blog/how-to-use-react-context-effectively
    • https://reactjs.org/docs/hooks-reference.html#usecontext
    • https://reactjs.org/docs/hooks-reference.html#usereducer
    • https://medium.com/swlh/react-router-route-configuration-968f4aac7fab
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Adaware Oghenero

      Related Posts

      Streamlining Resource Allocation for Enhanced Project Success

      December 18, 2024

      Conducting Effective Post-Project Evaluations: A Guide

      December 16, 2024

      Strategies for Keeping Projects on Track and Meeting Deadlines

      December 10, 2024
      Leave A Reply Cancel Reply

      You must be logged in to post a comment.

      Stay In Touch
      • Facebook
      • Twitter
      • Pinterest
      • Instagram
      • YouTube
      • Vimeo
      Don't Miss
      Express.js April 25, 2023

      Anime.js to MP4 and GIF with Node.js and FFMPEG

      While canvas animation is often considered the simpler approach for exporting animations to video and GIF formats, it can also limit the range of animations that can be created. Although complex and advanced animations are a possibility, it can quickly become a memory-intensive operation, especially when exporting to popular animation formats.

      18. Node.js Lessons. Work With Files. Fs Module

      October 20, 2016

      Nurturing LinkedIn Prospects Through Consistent Engagement

      November 25, 2024

      Enhancing Business Success: The Impact of Emotional Intelligence

      November 26, 2024

      Categories

      • AI & Automation
      • Angular
      • ASP.NET
      • AWS
      • B2B Leads
      • Beginners
      • Blogs
      • Business Growth
      • Case Studies
      • Comics
      • Consultation
      • Content & Leadership
      • CSS
      • Development
      • Django
      • E-commerce & Retail
      • Entrepreneurs
      • Entrepreneurship
      • Events
      • Express.js
      • Facebook Ads
      • Finance & Fintech
      • Flask
      • Flutter
      • Franchising
      • Funnel Strategy
      • Git
      • GraphQL
      • Home Services Marketing
      • Influencer & Community
      • Interview
      • Java
      • Java Spring
      • JavaScript
      • Job
      • Laravel
      • Lead Generation
      • Legal & Compliance
      • LinkedIn
      • Machine Learning
      • Marketing Trends
      • Medical Marketing
      • MSP Lead Generation
      • MSP Marketing
      • NestJS
      • Next.js
      • Node.js
      • Node.js Lessons
      • Paid Advertising
      • PHP
      • Podcasts
      • POS Tutorial
      • Programming
      • Programming
      • Python
      • React
      • React Lessons
      • React Native
      • React Native Lessons
      • Recruitment
      • Remote Job
      • SaaS & Tech
      • SEO & Analytics
      • Soshace
      • Startups
      • Swarm Intelligence
      • Tips
      • Trends
      • Vue
      • Wiki
      • WordPress
      Top Posts

      Facilisi Nullam Vehicula Ipsum Arcu Cursus Vitae Congue

      Trends January 28, 2020

      28 Sample Interview Questions for JavaScript Developers | Theory and Practice

      Interview February 27, 2019

      2. Уроки Node.js. Модули Часть 2

      Programming September 6, 2016

      Optimizing LinkedIn Lead Generation: Seamless CRM Integration

      LinkedIn December 7, 2024

      Subscribe to Updates

      Get The Latest News, Updates, And Amazing Offers

      About Us
      About Us

      Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

      7901 4th St N, Suite 28690
      Saint Petersburg, FL 33702-4305
      Phone: 1(877)SOSHACE

      Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
      Our Picks
      JavaScript

      Top 11 Django Interview Questions

      Entrepreneurship

      Three Latest Books Every Entrepreneur Should Read | Best Business Books

      Events

      Top IT Conferences and Events in 2020

      Most Popular

      Happy New 2020 Year!

      Soshace

      7. Уроки Node.js. Модуль Console

      Programming

      Basic Prototype Design

      Beginners
      © 2025 Soshace Digital.
      • Home
      • About
      • Services
      • Contact Us
      • Privacy Policy
      • Terms & Conditions

      Type above and press Enter to search. Press Esc to cancel.