EN
React - async image loading
12 points
In this short article, we would like to show how to load images in an async mode in React.
Quick solution (add loading="lazy"
to img
elements):
xxxxxxxxxx
1
<img src="https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" loading="lazy" />
As async mode we understand the images loading occurs after all resources are loaded, do not blocking other sync resources loading. That approach speeds up page loading by splitting the loading process into 2 steps:
- page loading (without async images) - we see all necessary things in the correct way faster,
- async images loading - images are loaded when the page is ready.

The main advantage of this solution is the web browser decides when image should be loaded to achieve the best performance.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<img src="https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" loading="lazy" />
5
<p>Some text here ...</p>
6
<img src="https://dirask.com/static/bucket/1590005168287-pPLQqVWYa9--image.png" loading="lazy" />
7
<p>Some text here ...</p>
8
<img src="https://dirask.com/static/bucket/1590005138496-MWXQzxrDw4--image.png" loading="lazy" />
9
<p>Some text here ...</p>
10
<img src="https://dirask.com/static/bucket/1590005318053-3nbAR5nDEZ--image.png" loading="lazy" />
11
</body>
12
</html>
In this section you can find solutuion that lets to load images in async mode, even the browser doesn't support loading="lazy"
.
xxxxxxxxxx
1
//import React from 'react';
2
//import ReactDOM from 'react-dom';
3
4
const AsyncImage = (props) => {
5
const [loadedSrc, setLoadedSrc] = React.useState(null);
6
React.useEffect(() => {
7
setLoadedSrc(null);
8
if (props.src) {
9
const handleLoad = () => {
10
setLoadedSrc(props.src);
11
};
12
const image = new Image();
13
image.addEventListener('load', handleLoad);
14
image.src = props.src;
15
return () => {
16
image.removeEventListener('load', handleLoad);
17
};
18
}
19
}, [props.src]);
20
if (loadedSrc === props.src) {
21
return (
22
<img {props} />
23
);
24
}
25
return null;
26
};
27
28
const App = () => {
29
return (
30
<div>
31
<AsyncImage src="https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" />
32
<p>Some text here ...</p>
33
<AsyncImage src="https://dirask.com/static/bucket/1590005168287-pPLQqVWYa9--image.png" />
34
<p>Some text here ...</p>
35
<AsyncImage src="https://dirask.com/static/bucket/1590005138496-MWXQzxrDw4--image.png" />
36
<p>Some text here ...</p>
37
<AsyncImage src="https://dirask.com/static/bucket/1590005318053-3nbAR5nDEZ--image.png" />
38
</div>
39
);
40
};
41
42
const root = document.querySelector('#root');
43
ReactDOM.render(<App />, root);