Conditional Rendering in React – Displaying Loading and Error States for Asynchronous Data

Conditional rendering in React is a powerful tool for controlling what appears in the UI based on different states. This article explains how to show a “Loading…” message while asynchronous data is being fetched, and how to display an error message if the request fails. Using useState and useEffect, we manage isLoading and isError flags, and render content dynamically using ternary and logical operators.

isLoadingisErroruseEffect

~2 min read • Updated Oct 22, 2025

Introduction


In React applications, data is often fetched asynchronously. During this process, showing feedback like “Loading…” or “Something went wrong” improves user experience. This article demonstrates how to implement conditional rendering for such states using React’s built-in hooks and JSX logic.


Managing Loading State with isLoading


First, define a boolean state to track loading:


const [isLoading, setIsLoading] = React.useState(false);

Then toggle it during data fetching:


React.useEffect(() => {
  setIsLoading(true);
  getAsyncStories().then((result) => {
    setStories(result.data.stories);
    setIsLoading(false);
  });
}, []);

Conditional Rendering with Ternary Operator


Use a ternary operator to show either the loading message or the list:


{isLoading ? (
  <p>Loading ...</p>
) : (
  <List list={searchedStories} onRemoveItem={handleRemoveStory} />
)}

Handling Errors with isError


Define another state to track errors:


const [isError, setIsError] = React.useState(false);

Update it in the catch block:


getAsyncStories()
  .then((result) => {
    setStories(result.data.stories);
    setIsLoading(false);
  })
  .catch(() => setIsError(true));

Conditional Rendering with Logical &&


Use the logical && operator to show the error message only when needed:


{isError && <p>Something went wrong ...</p>}

If isError is true, the message is rendered. Otherwise, nothing is shown.


Conclusion


Conditional rendering in React is essential for managing UI feedback during asynchronous operations. With useState and useEffect, we can track loading and error states, and use JSX logic to dynamically render appropriate messages. These techniques help build responsive and user-friendly interfaces.


Written & researched by Dr. Shahin Siami