How to show a loading screen while logging in in React.

I originally built my app without rendering a loading screen on the login/sign-up pages while a user is logging in. The result? A user not knowing what on earth is going on and whether they had truly clicked “Log in”.

I knew I had to implement a simple way for a user to know that their logging in request is being processed and in this article, I’d go into the details on how I achieved this.

This article assumes that you know how to setup a react app and how to make a post request to authenticate a user. I’d also be using React Hooks but the idea is the same if implementing it using react classes.

  1. Create your Login Page and setup your Post request.Here’s a snippet of my handleSubmit function. I’m using Axios to make a post request here.
handleSubmit function for when a user is signing up

2. Create a react component that contains a Spinner svg icon and also import its CSS. For this tutorial I’m using the SVG icon by Supah. Here’s the codepen for the SVG styles. Make sure to also copy the CSS from the codepen as we need it to animate our spinner. See below for how I created my SVG Icon component.

I’ve added some extra css to give the spinner a background and some opacity.

3. Inside your Login component, import the SVG icon component, then create a hook that let’s us set the state of the app. Originally, our default state is set to empty.

importing the spinner component
React hook to track the state of our logging in.

4. Now, once a user clicks the login button, we want to immediately update the loggedInState. See below for a snippet. I’ve updated my loggedInState to “logging in”. Now we can use this state to get our spinner to render.

5. Inside our return within our main div, we use the ternary operator to render the spinner if the state is “logging in” else we render nothing.

rendering if the state is logging in.

See before and after pictures of my app below.

Before
After applying spinner

Done!

Full-stack Engineer. Rails/Node.js/React. I love plantain chips! Reach me at Adebola.dev.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store