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.
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);
});
}, []);Use a ternary operator to show either the loading message or the list:
{isLoading ? (
<p>Loading ...</p>
) : (
<List list={searchedStories} onRemoveItem={handleRemoveStory} />
)}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));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.
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.