React User Login Authentication using useContext and useReducer.

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.

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.

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.

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.

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:

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

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:

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:

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:

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:

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

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:

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

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.

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

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

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:

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

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:

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:

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 :

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:

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:

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.

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:

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.

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:

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.

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:

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:

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:

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:

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.

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

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.

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:

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

About the author

Stay Informed

It's important to keep up
with industry - subscribe!

Stay Informed

Looks good!
Please enter the correct name.
Please enter the correct email.
Looks good!

Related articles

Create simple POS with React.js, Node.js, and MongoDB #17: Stat screen

Now, we are going to implement the final chapter for this tutorial series where we are implementing a graphical representation section on our ...

16.10.2020

How to write effective tests for React apps with react testing library?

Testing might seem like extra work at first. Why write tests when you could be delivering features for your application? Writing tests may seem like ...

Create simple POS with React.js, Node.js, and MongoDB #16: Order Screen

In this chapter, we are going to create an order page. The order page displays the products and the calculator to help calculate the total price. ...

No comments yet

Sign in

Forgot password?

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy

Password recovery

You can also try to

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy