To fetch image from API with React, we can use the fetch function.
For instance, we write:
import React, { useEffect, useState } from "react";
const imageUrl = "https://i.imgur.com/fHyEMsl.jpg";
export default function App() {
const [img, setImg] = useState();
const fetchImage = async () => {
const res = await fetch(imageUrl);
const imageBlob = await res.blob();
const imageObjectURL = URL.createObjectURL(imageBlob);
setImg(imageObjectURL);
};
useEffect(() => {
fetchImage();
}, []);
return (
<>
<img src={img} alt="icons" />
</>
);
}
We call fetch with the imageUrl to make a GET request to it.
Then we call res.blob to convert the response object to a blob.
Next, we call URL.createObjectURL with the imageBlob to convert it to a URL string that we can set as the src attribute of the img element.
Finally, we call setImg with imageObjectURL so we can set img as the value of src to display it.
Conclusion To fetch image from API with React, we can use the fetch function.
2025 version:
import React, { useEffect, useState } from "react";
const imageUrl = "https://i.imgur.com/fHyEMsl.jpg";
export default function App() {
const [img, setImg] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const abortCtrl = new AbortController();
let objectUrl: string | null = null;
async function fetchImage() {
try {
const res = await fetch(imageUrl, { signal: abortCtrl.signal });
if (!res.ok) throw new Error("Network error");
const blob = await res.blob();
objectUrl = URL.createObjectURL(blob);
setImg(objectUrl);
} catch (err: any) {
if (err.name !== "AbortError") {
setError("Failed to load image");
}
} finally {
setLoading(false);
}
}
fetchImage();
// cleanup: release object URL + abort fetch
return () => {
if (objectUrl) URL.revokeObjectURL(objectUrl);
abortCtrl.abort();
};
}, []);
if (loading) return <p>Loading…</p>;
if (error) return <p style={{ color: "red" }}>{error}</p>;
return <img src={img!} alt="icons" style={{ maxWidth: "100%" }} />;
}