Utilizing spinners in your React webpages

Loading spinners are essential components of modern web applications, and they play a crucial role in enhancing the user experience. A loading spinner, also known as a "spinner," is a common UI element that displays while data is being loaded. It provides feedback to the user that an action is being performed and prevents them from assuming the application has frozen.

React-spinner is a library that provides a set of pre-designed spinners for use in your React applications, making the integration of these spinners quick and easy for developers, as there is no need for custom styling and animations. The library provides a wide range of spinner styles to choose from, making it easy to find one that matches the design of the application.

Prerequisites

You need to understand the following concepts in order to follow along easily:

  • How to create a React app

  • Installing packages in a React app with a package manager like npm or yarn.

  • Importing components from an installed package into your app

  • React useState and useEffect hooks.

  • Fetching data from an API with the inbuilt fetch API

Understanding the react-spinner Library

Installation of the react-spinner-library

To use the react-spinner library, you need to first install it using npm or yarn. The following command will install the library:

npm install react-spinner

OR

yarn add react-spinner

Once you install the library, you will have access to all the spinners in it. Some of the available styles include your basic bar loader, a circular spinner, a rotating plane, a double bounce, a wave, and many others. You can find all of them here.

Each spinner can accept props which can be used to customize various properties of the spinner. These props are:

  • size: used to specify the size of the loader. The default unit is in px.

  • height: used to specify the height of the loader. The default unit is in px.

  • width: used to specify the width of the loader. The default unit is in px.

  • color: used to specify the colour of the loader. It can accept any string of hexcode, and also has some basic colours.

  • margin: used to specify the margin of the loader in which it can be applied. The default unit is in px.

  • loading: this is a boolean value that specifies whether the loader is shown or not.

  • cssOverride: this prop takes in a CSS string that can include any valid CSS styles that can be applied to an HTML element.

  • speedMultiplier: this takes in a valid number that is used to control the speed of animation.

It's important to note that these props are not applicable to all spinner components in the react-spinners library, as certain props can only be used in certain spinner components. Therefore, it is important to check the documentation for the specific props of the spinner component you wish to use to see if the prop is supported and how to use it correctly.

Importing spinner styles into the React application

To import a spinner style into your React app, you need to first import the spinner component from the react-spinner library. You can then use the spinner component in your app by calling on its name. The following code shows an example of how to import and use the BarLoader spinner style:


import { useState } from "react";
import { BarLoader } from "react-spinners";

function App {
    const [loading, setLoading] = useState(true);
   return (
      <div>
        <BarLoader loading={loading} color={purple}/>  
      </div>
   );
}

The code showcases the utilization of the BarLoader component, sourced from the react-spinner library, within the application. This results in the rendering of the specified BarLoader style within the App component.

Let’s implement react-spinners in a real-world application

To observe react-spinners in action, let's build an app that fetches a random joke from the random joke API. Once the app mounts, the function to fetch data from the API is initiated. While waiting for the API to return the requested information, a loading spinner will be displayed. As soon as the requested data has been fetched, the spinner disappears, and the data is displayed. The user may also initiate a new joke retrieval by pressing a button, the loading spinner is also displayed until the new joke is obtained and displayed.

To begin, create a React app, and clean up the app.

Let’s create the basic app that fetches data from the API. To do this:

  • We create a function to fetch the data,

  • Use the built-in useEffect hook to run this function once this app mounts.

  • We also create a button which when clicked fetches new data from the API and also displays it.


import { useState, useEffect } from "react";
import "./App.css";

function App() {
  const [joke, setJoke] = useState({});
  const [showAnswer, setShowAnswer] = useState(false);

  const fetchJoke = () => {
    fetch("https://official-joke-api.appspot.com/random_joke")
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        setJoke(data);
      });
  };

  useEffect(() => {
    fetchJoke();
  }, []);

  return (
    <div className="App">
          <div className="joke__container">{joke.setup}</div>
          <button
            className="showAnswerButton"
            onClick={() => {
              setShowAnswer(!showAnswer);
            }}
          >
            Click to see answer
          </button>
          <div>{showAnswer && joke.punchline}</div>
          <div className="newJokeButton">
            <button
              onClick={() => {
                fetchJoke();
                setShowAnswer(false);
              }}
            >
              New Joke
            </button>
          </div> 
    </div>
  );
}
export default App;

The application we have developed effectively retrieves data from the API and displays this data when it has been fetched, however, during the wait time for the data, the page remains blank, resulting in a diminished user experience and potential confusion for the user regarding the status of the data retrieval.

Let’s now add a loading spinner to the app, so anytime the data is fetching, a loading spinner will be displayed.

  1. Ensure the react spinner library has been installed.

  2. Import the loader from the react-spinner library

  3. Create a loading state to keep track of the loading state.

  4. In the fetchJoke function, we set the loading state to true before fetching the data. While the data is loading, we display the spinner. Once the data is fetched, we set the loading state to false. The loading spinner disappears and the data is assigned to the joke variable.

  5. In the return statement, we use a ternary operator to display either the spinner or app information based on the loading state.


import { useState, useEffect } from "react";
import "./App.css";
import { HashLoader } from "react-spinners";
function App() {
  const [joke, setJoke] = useState({});
  const [loading, setLoading] = useState(true);
  const [showAnswer, setShowAnswer] = useState(false);
  const fetchJoke = () => {
    setLoading(true);
    fetch("https://official-joke-api.appspot.com/random_joke")
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        setLoading(false);
        setJoke(data);
      });
  };
  useEffect(() => {
    fetchJoke();
  }, []);
  return (
    <div className="App">
      {loading ? (
        <div>
          <HashLoader
            loading={loading}
            color="#202020"
            aria-label="Loading Spinner"
          />
        </div>
      ) : (
        <div>
          <div className="joke__container">{joke.setup}</div>
          <button
            className="showAnswerButton"
            onClick={() => {
              setShowAnswer(!showAnswer);
            }}
          >
            Click to see answer
          </button>
          <div>{showAnswer && joke.punchline}</div>
          <div className="newJokeButton">
            <button
              onClick={() => {
                fetchJoke();
                setShowAnswer(false);
              }}
            >
              New Joke
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
export default App;

You can check out a live demo of the webapp here.

Conclusion

In conclusion, spinners are an essential component in creating a smooth and engaging user experience on React web pages. They provide visual cues to users while data is being loaded, thereby preventing confusion and frustration. By utilizing spinners, React developers can create web pages that are more responsive and performant.

The react-spinner library is a great tool for adding dynamic spinners to your React applications. With its ease of use and customizable options, it's a great choice for any project. You'll be able to provide a better user experience and optimize your application's performance, making it a win-win for both you and your users.