DEV Community

Cover image for 3 Ways To Create Engaging React Loading Screens with Hooks
Mark Yu
Mark Yu

Posted on

3 Ways To Create Engaging React Loading Screens with Hooks

Creating engaging loading screens for your React applications can greatly enhance the user experience, especially during data fetching or other intensive operations. This article explores three dynamic methods to achieve this using React Hooks. These methods vary in complexity and offer different levels of customization, ensuring you can cater to your specific needs.

Image description

Type 1: Using react-loading

The react-loading library is a great choice for a straightforward and effective loading screen. It offers a variety of loading indicators that can be easily customized. The implementation is simple and does not require extensive setup.

  1. Setup: Create a new React component file, PreLoader1.js.

  2. Functional Component: Within this file, create a functional component and use two states:

   const [data, setData] = useState([]);
   const [done, setDone] = useState(false);
Enter fullscreen mode Exit fullscreen mode
  • Data: Holds the data fetched from the API.
  • Done: A boolean that determines whether to display the pre-loader.
  1. Fetch Data:
  • Use the useEffect hook to fetch data from an API:
   useEffect(() => {
      setTimeout(() => {
         fetch("https://jsonplaceholder.typicode.com/posts")
            .then(response => response.json())
            .then(json => {
               setData(json);
               setDone(true);
            });
      }, 2000);
   }, []);
Enter fullscreen mode Exit fullscreen mode
  • The setTimeout function adds a delay for showcasing the loading screen.
  1. Render:
  • If done is false, render the loading indicator. Otherwise, display the fetched data:
   return (
      <>
         {!done ? (
            <ReactLoading type="spin" color="#000" height={50} width={50} />
         ) : (
            <ul>
               {data.map(item => (
                  <li key={item.id}>{item.title}</li>
               ))}
            </ul>
         )}
      </>
   );
Enter fullscreen mode Exit fullscreen mode

Type 2: Using react-lottie

For more sophisticated animations, the react-lottie library is an excellent choice. This method allows you to display engaging animations that align with your app's theme.

  1. Setup: Start by creating a file, PreLoader2.js, and importing react-lottie:
   import Lottie from "react-lottie";
Enter fullscreen mode Exit fullscreen mode
  1. Download Animations: Obtain Lottie animations from lottiefiles.com and import them into your project:
   import * as location from "../1055-world-locations.json";
   import * as success from "../1127-success.json";
Enter fullscreen mode Exit fullscreen mode
  1. Set Options: Configure the animation settings:
   const defaultOptions1 = {
      loop: true,
      autoplay: true,
      animationData: location.default,
      rendererSettings: {
         preserveAspectRatio: "xMidYMid slice",
      },
   };

   const defaultOptions2 = {
      loop: true,
      autoplay: true,
      animationData: success.default,
      rendererSettings: {
         preserveAspectRatio: "xMidYMid slice",
      },
   };
Enter fullscreen mode Exit fullscreen mode
  1. Use States:
  • Use three states to manage the loading animations:
   const [data, setData] = useState([]);
   const [loading, setLoading] = useState(false);
   const [completed, setCompleted] = useState(false);
Enter fullscreen mode Exit fullscreen mode
  1. Fetch Data:
  • Similar to Type 1, but with two loading indicators:
   useEffect(() => {
      setTimeout(() => {
         fetch("https://jsonplaceholder.typicode.com/posts")
            .then(response => response.json())
            .then(json => {
               setData(json);
               setLoading(true);
               setTimeout(() => {
                  setCompleted(true);
               }, 1000);
            });
      }, 2000);
   }, []);
Enter fullscreen mode Exit fullscreen mode
  1. Render:
   return (
      <>
         {!completed ? (
            <>
               {!loading ? (
                  <Lottie options={defaultOptions1} height={200} width={200} />
               ) : (
                  <Lottie options={defaultOptions2} height={100} width={100} />
               )}
            </>
         ) : (
            <h1>Your Data</h1>
         )}
      </>
   );
Enter fullscreen mode Exit fullscreen mode

Type 3: Using Simple CSS

For a minimalist approach, you can create a loading screen using simple CSS styling. This method gives you full control over the design but requires a bit more effort.

  1. Setup: Create a new file, PreLoader3.js, and copy the setup from PreLoader2.js.

  2. Remove Lottie: Delete all code related to react-lottie and update the return statement:

   return (
      <>
         {!completed ? (
            <>
               {!loading ? (
                  <div className="spinner">
                     <span>Loading...</span>
                     <div className="half-spinner"></div>
                  </div>
               ) : (
                  <div className="completed">&#x2713;</div>
               )}
            </>
         ) : (
            <h1>Your Data</h1>
         )}
      </>
   );
Enter fullscreen mode Exit fullscreen mode
  1. Styling: Create a CSS file named preloader3.css to style the spinner and success symbol.

Conclusion

These three approaches offer different levels of customization and complexity for creating engaging loading screens in React applications. Whether you prefer using libraries or crafting custom CSS animations, these methods provide flexible solutions to enhance user experience during data fetching or processing tasks.

Top comments (0)