Improve your React application loading speed with async images

3 points
Created by:
Dirask Community

Hi there! 👋 😊

Did you know that if you┬áload images after the page is loaded, the user will see the content earlier and SEO tools┬áwill detect that the page loads faster? 🚀📈

In this article, I want to show you how to create a simple component in React by which the graphics are loaded after all resources are loaded.

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 right order sooner,
  • async┬áimages loading - images are loaded when the page is ready.

Final effect:

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

Arrows mark lines when images are loaded after rendering the page (when it's ready).

Below I present you a solution in which I create an in-memory only image that, after is loaded, signals to display the proper image in React on the web page.

Runnable example:

// ONLINE-RUNNER:browser;

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

const AsyncImage = (props) => {
  	const [loadedSrc, setLoadedSrc] = React.useState(null);
  	React.useEffect(() => {
      	if (props.src) {
          	const handleLoad = () => {
            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 (
        <AsyncImage src="" />
        <p>Some text here ...</p>
        <AsyncImage src="" />
        <p>Some text here ...</p>
        <AsyncImage src="" />
        <p>Some text here ...</p>
        <AsyncImage src="" />

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

I recommend copying the solution to your local React project, open developer tools in your browser and then run the application to see the result.

If you found this article┬áuseful and would like to receive more content like this, you could react to this post, which would make me very happy.😊

See you in the next posts! 🖐


ReactJS - Blog posts

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.

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