handling loading and error state in React js 2025
Handling Loading and Error State in React JS 2025
When fetching data in React, it's important to manage loading and error states to provide a better user experience.
Example:
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch('https://pokeapi.co/api/v2/pokemon/pikachu')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(json => {
setData(json);
setLoading(false);
})
.catch(err => {
setError(err.message);
setLoading(false);
});
}, []);
if (loading) return Loading...
;
if (error) return Error: {error}
;
return (
{data.name}
);
}
export default DataFetcher;
Output Behavior:
- Initially displays
Loading...
- If there's an error (e.g., invalid API), shows the error message
- On success, displays the Pokémon name and image