Skip to content
Related Articles

Related Articles

How to display a simple loading indicator between routes in react router ?

View Discussion
Improve Article
Save Article
  • Last Updated : 10 May, 2021
View Discussion
Improve Article
Save Article

It is a good practice to display a loading screen while you prepare your page to display. It is very easy to display a simple loading indicator between routes in react-router. 

Creating React Application:

  • Step 1: Create a React application using the following command:

    npx create-react-app foldername
  • Step 2: After creating your project folder i.e. foldername, move to it using the following command:

    cd foldername

Project Structure: It will look like the following.

Create Home.js and App.js as shown in the above image.

Implementation: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.


import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import {useState} from "react";
import Home from'./components/Home';
function App() {
  return (
    // Create route for each page, since we 
    // have only one page. So we are defining 
    // only one route.
      <Route path="/" exact component={Home} />
export default App;


import React from "react";
import {useEffect, useState} from "react";
const Home = () => {
    // Set loading state to true initially
    const [loading, setLoading] = useState(true);
    useEffect(() => {
      // Loading function to load data or 
      // fake it using setTimeout;
      const loadData = async () => {
        // Wait for two second
        await new Promise((r) => setTimeout(r, 2000));
        // Toggle loading state
        setLoading((loading) => !loading);
    }, [])
    // If page is in loading state, display 
    // loading message. Modify it as per your 
    // requirement.
    if (loading) {
        return <div>Loading....</div>
    // If page is not in loading state, display page.
    else {
        return <h1>Home</h1>
export default Home;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!