Languages
[Edit]
EN

React - async image loading

12 points
Created by:
AnnLen
11260

In this short article we would like to show how to load images in async mode in React. As async mode we understand the images loading occurs after all reasources are loaded do not blocking other sync resources loading. That approach speed up page loading by splitting loading process into 2 steps:

  • page loading (without async images) - we see all necessary things in correct way faster,
  • async┬áimages loading - images are loaded when page is ready.
Images async loading proof in Google Chrome DevTools - loaded after blue and red lines.
Images async loading proof in Google Chrome DevTools - loaded after blue and red lines.

Practical example:

// ONLINE-RUNNER:browser;

//import React from 'react';
//import ReactDOM from 'react-dom';

const AsyncImage = (props) => {
  	const [loadedSrc, setLoadedSrc] = React.useState(null);
  	React.useEffect(() => {
      	setLoadedSrc(null);
      	if (props.src) {
          	const handleLoad = () => {
            	setLoadedSrc(props.src);
            };
            const image = new Image();
            image.addEventListener('load', handleLoad);
          	image.src = props.src;
            return () => {
              	image.removeEventListener('load', handleLoad);
            };
        }
    }, [props.src]);
  	if (loadedSrc === props.src) {
        return (
            <img {...props} />
        );
    }
  	return null;
};

const App = () => {
    return (
      <div>
        <AsyncImage src="https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png" />
        <p>Some text here ...</p>
        <AsyncImage src="https://dirask.com/static/bucket/1590005168287-pPLQqVWYa9--image.png" />
        <p>Some text here ...</p>
        <AsyncImage src="https://dirask.com/static/bucket/1590005138496-MWXQzxrDw4--image.png" />
        <p>Some text here ...</p>
        <AsyncImage src="https://dirask.com/static/bucket/1590005318053-3nbAR5nDEZ--image.png" />
      </div>
    );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join