Mahamudul Hasan Rubel
HomeAboutProjectsSkillsExperienceBlogCoursesPhotosContact
Mahamudul Hasan Rubel

Senior Software Engineer crafting high-performance web applications and SaaS platforms.

Navigation

  • Home
  • About
  • Projects
  • Skills
  • Experience
  • Blog
  • Courses
  • Photos
  • Contact

Get in Touch

Available for senior/lead roles and consulting.

bd.mhrubel@gmail.comHire Me

© 2026 Mahamudul Hasan Rubel. All rights reserved.

Built with using Next.js 16 & Tailwind v4

Back to Blog
Lesson 26 of the React Fundamentals: Build Modern UIs from Scratch course
ReactJune 25, 20263 min read

Handling Loading States in React: Improving UX and Performance

Learn to master loading state in React to improve UX. Discover how to conditionally render spinners while your API fetches data for your movie app.

Reactloading stateUXconditional renderinghooksstate managementjavascriptfrontend

Previously in this course, we covered fetching data from an API to populate our application. While that allows us to retrieve data, it introduces a "gap" in the user experience: the time between the request being sent and the data arriving. If we simply leave the UI blank during this interval, users often assume the app is broken.

In this lesson, we will implement a robust loading state to bridge that gap. By managing a dedicated state variable and applying conditional rendering, we can show the user that something is happening, significantly improving the perceived performance of our movie browser.

Why Loading States Matter for UX

In a real-world application, network latency is unpredictable. Even a fast API can take 500ms to respond, which feels like an eternity on the web. By explicitly showing a "Loading..." message or a CSS spinner, we provide immediate feedback. This simple shift in UX transforms a perceived "hang" into a managed data-fetching process.

Managing Loading State

To track whether our data is currently being fetched, we introduce a new piece of state. We’ll use a boolean value: true when the request is in progress, and false once the data is returned or an error occurs.

Here is how we integrate this into our existing MovieList component:

JSX
import { useState, useEffect } from CE9178">'react';

function MovieList() {
  const [movies, setMovies] = useState([]);
  const [isLoading, setIsLoading] = useState(true); // 1. Initialize as true

  useEffect(() => {
    async function fetchMovies() {
      setIsLoading(true); // 2. Set to true before the fetch
      try {
        const response = await fetch(CE9178">'https://api.example.com/movies');
        const data = await response.json();
        setMovies(data);
      } catch (error) {
        console.error("Failed to fetch", error);
      } finally {
        setIsLoading(false); // 3. Always set to false when done
      }
    }

    fetchMovies();
  }, []);

  // 4. Conditional Rendering based on state
  if (isLoading) {
    return <div className="spinner">Loading movies...</div>;
  }

  return (
    <ul>
      {movies.map(movie => <li key={movie.id}>{movie.title}</li>)}
    </ul>
  );
}

The "Finally" Pattern

Notice the use of the finally block in the example above. This is a best practice. Whether the API call succeeds or fails, the loading state must be set back to false. Without it, if the API throws an error, your user would be stuck with a permanent "Loading..." indicator—a classic "dead-end" UI bug.

Hands-on Exercise: Add a Spinner to Your App

Building on our movie-browser project, locate your movie fetching component. Perform the following steps:

  1. Add a const [isLoading, setIsLoading] = useState(true); line to your component.
  2. Wrap your fetch call logic to set isLoading(true) at the start and setIsLoading(false) inside a finally block.
  3. In your JSX, use a ternary operator or an early return statement (as shown above) to display a simple paragraph or a CSS-styled spinner component when isLoading is true.
  4. Test this by opening your browser's "Network" tab in DevTools, setting the throttling to "Slow 3G," and refreshing the page to see your loading indicator in action.

Common Pitfalls

  • Forgetting the finally block: As mentioned, if you only set isLoading(false) inside the .then() or after the await, an error will leave your application in a permanent loading state.
  • Over-complicating state: Beginners often try to track "loading," "success," and "error" as separate state variables that might conflict. Start with a simple boolean. You can always evolve this into a state machine if your requirements grow.
  • Flickering indicators: If your API is extremely fast, the loading state might only appear for a few milliseconds, causing a "flicker." In production, some developers add a small delay to ensure the spinner is visible for at least 300ms to avoid visual noise.

Recap

Managing a loading state is a fundamental step in building professional React applications. By tracking the lifecycle of an asynchronous request, you can provide clear visual feedback, which is essential for a high-quality UX. We’ve learned to initialize our state, use finally to ensure clean transitions, and use conditional rendering to swap our view based on the current operation status.

Up next: Now that we have a loading state, we need to handle scenarios where the API request fails entirely; we'll cover managing errors in our next lesson.

Previous lessonFetching Data from an APINext lesson Managing Errors
Back to Blog

Similar Posts

ReactReactJune 25, 20263 min read

Fetching Data from an API: A Practical React Guide

Master the fetch API in React to retrieve external data. Learn to perform asynchronous requests and store JSON responses in your component state effectively.

Read more
ReactReactJune 25, 20263 min read

Part of the course

React Fundamentals: Build Modern UIs from Scratch

beginner · Lesson 26 of 49

  1. 1

    Introduction to Component-Based Architecture

    4 min
  2. 2

    Understanding the Virtual DOM

    4 min
  3. 3

    Setting Up with Vite

    3 min

Building a Movie Filter Toggle in React: A Beginner's Guide

Master the art of UI state management by adding a filter toggle to your movie app. Learn to control list rendering using boolean state and checkbox inputs.

Read more
ReactReactJune 25, 20264 min read

Rendering Lists of Data in React: A Practical Guide

Learn how to use the map method for list rendering in React. Master the key prop to keep your dynamic movie lists efficient, performant, and bug-free.

Read more
4

Mastering JSX Syntax

4 min
  • 5

    Creating Static Components

    3 min
  • 6

    Styling Components

    3 min
  • 7

    Passing Data with Props

    3 min
  • 8

    Dynamic Movie Cards

    3 min
  • 9

    Component Composition

    3 min
  • 10

    Conditional Rendering

    3 min
  • 11

    Rendering Lists of Data

    4 min
  • 12

    The Key Prop Explained

    4 min
  • 13

    Introduction to React State

    4 min
  • 14

    Managing State with useState

    3 min
  • 15

    Building an Interactive Search Bar

    3 min
  • 16

    Handling Click Events

    4 min
  • 17

    Updating State Based on Previous State

    4 min
  • 18

    Filtering the Movie List

    3 min
  • 19

    Handling Form Submissions

    3 min
  • 20

    Controlled Components

    4 min
  • 21

    Event Bubbling and Propagation

    3 min
  • 22

    Building a Movie Filter Toggle

    3 min
  • 23

    Introduction to Side Effects

    4 min
  • 24

    useEffect Dependencies

    4 min
  • 25

    Fetching Data from an API

    3 min
  • 26

    Handling Loading States

    3 min
  • 27

    Managing Errors

    3 min
  • 28

    Cleanup Functions in useEffect

    3 min
  • 29

    Debouncing Search Input

    3 min
  • 30

    Refactoring for Clean Code

    3 min
  • 31

    Folder Structure Best Practices

    4 min
  • 32

    Extracting Custom Hooks

    3 min
  • 33

    Prop Drilling and Context API

    3 min
  • 34

    Polishing the UI

    Coming soon
  • 35

    Finalizing the Movie Browser

    Coming soon
  • 36

    Review of Component Lifecycle

    Coming soon
  • 37

    Review of State Management

    Coming soon
  • 38

    Building a Modal Component

    Coming soon
  • 39

    Introduction to PropTypes

    Coming soon
  • 40

    Performance Optimization Basics

    Coming soon
  • 41

    Handling Browser History

    Coming soon
  • 42

    Working with LocalStorage

    Coming soon
  • 43

    Building a Favorites List

    Coming soon
  • 44

    Handling Media in React

    Coming soon
  • 45

    Introduction to Testing

    Coming soon
  • 46

    Debugging React Apps

    Coming soon
  • 47

    Deployment Basics

    Coming soon
  • 48

    Using External Libraries

    Coming soon
  • 49

    Advanced

    Coming soon
  • View full course