3 Ways To Create Engaging React Loading Screens with Hooks
Tags: react, hooks, webdev, frontendchallenge
Published: 2024-05-03 05:10:42

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b4xmw0yj1ddbqfoyczmh.png)

### 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:

   ```js
   const [data, setData] = useState([]);
   const [done, setDone] = useState(false);
   ```

   - Data: Holds the data fetched from the API.
   - Done: A boolean that determines whether to display the pre-loader.

3. **Fetch Data:**

   - Use the `useEffect` hook to fetch data from an API:

   ```js
   useEffect(() => {
      setTimeout(() => {
         fetch("https://jsonplaceholder.typicode.com/posts")
            .then(response => response.json())
            .then(json => {
               setData(json);
               setDone(true);
            });
      }, 2000);
   }, []);
   ```

   - The `setTimeout` function adds a delay for showcasing the loading screen.

4. **Render:**

   - If `done` is false, render the loading indicator. Otherwise, display the fetched data:

   ```js
   return (
      <>
         {!done ? (
            <ReactLoading type="spin" color="#000" height={50} width={50} />
         ) : (
            <ul>
               {data.map(item => (
                  <li key={item.id}>{item.title}</li>
               ))}
            </ul>
         )}
      </>
   );
   ```

### 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`:

   ```js
   import Lottie from "react-lottie";
   ```

2. **Download Animations:** Obtain Lottie animations from `lottiefiles.com` and import them into your project:

   ```js
   import * as location from "../1055-world-locations.json";
   import * as success from "../1127-success.json";
   ```

3. **Set Options:** Configure the animation settings:

   ```js
   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",
      },
   };
   ```

4. **Use States:**

   - Use three states to manage the loading animations:

   ```js
   const [data, setData] = useState([]);
   const [loading, setLoading] = useState(false);
   const [completed, setCompleted] = useState(false);
   ```

5. **Fetch Data:**

   - Similar to Type 1, but with two loading indicators:

   ```js
   useEffect(() => {
      setTimeout(() => {
         fetch("https://jsonplaceholder.typicode.com/posts")
            .then(response => response.json())
            .then(json => {
               setData(json);
               setLoading(true);
               setTimeout(() => {
                  setCompleted(true);
               }, 1000);
            });
      }, 2000);
   }, []);
   ```

6. **Render:**

   ```js
   return (
      <>
         {!completed ? (
            <>
               {!loading ? (
                  <Lottie options={defaultOptions1} height={200} width={200} />
               ) : (
                  <Lottie options={defaultOptions2} height={100} width={100} />
               )}
            </>
         ) : (
            <h1>Your Data</h1>
         )}
      </>
   );
   ```

### 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:

   ```js
   return (
      <>
         {!completed ? (
            <>
               {!loading ? (
                  <div className="spinner">
                     <span>Loading...</span>
                     <div className="half-spinner"></div>
                  </div>
               ) : (
                  <div className="completed">&#x2713;</div>
               )}
            </>
         ) : (
            <h1>Your Data</h1>
         )}
      </>
   );
   ```

3. **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.