DEV Community

Cover image for React - async image loading
Dirask-React
Dirask-React

Posted on • Originally published at dirask.com

React - async image loading

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? 🚀📈

Before we start, I would highly recommend you to check out runnable example for the solution on our website: React - async image loading

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 two 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:image
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.

Practical example:

import React from 'react';

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>
    );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

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! 🖐


Write to us! ✉

If you have any problem to solve or questions that no one can answer related to a React or JavaScript topic, or you're looking for a mentoring write to us on dirask.com -> Questions

Oldest comments (10)

Collapse
 
buriti97 profile image
buridev • Edited

i will try today, thanks

Collapse
 
myzel394 profile image
Myzel394

I think you can achieve the same by simply using native lazy loading.
web.dev/browser-level-image-lazy-l...

Collapse
 
nirmal15mathew profile image
Nirmal Thomas Mathew

Yes, we can. But I think it will be more useful if we combine the browser level lazy loading and create an image component which can be reused

Collapse
 
talorlanczyk profile image
TalOrlanczyk

Well you can do like medium and save a small version of an image and it by default will make it blur and once it load you replace with a real one
But still great job and its really important stuff great job

Collapse
 
edimeri profile image
Erkand Imeri • Edited

Where did you get this?

I mean the new Image() class?

const image = new Image();

Collapse
 
georgexchelebiev profile image
George Chelebiev
Collapse
 
lizgarcia16 profile image
Laura Lizet Garcia Garcia

Greetings, your code has helped me a lot, but I'm trying to get the coverage in the unit tests (with react testing library), and I'm stuck in the part to get to the load listener to get to the return of the image, do you happen to know how I could reach the coverage of 100 component that you did?

Collapse
 
elliot_brenya profile image
Elliot Brenya sarfo

For reaching 100% coverage on the component with React Testing Library, I would suggest trying to test the component's state and props after the image load event. You can do this by using the waitForElement function from React Testing Library to wait for the image to load, and then use getByTestId to access the component's state and props. Additionally, you could also test the component's handling of the error event by mocking the image load to fail and checking that the component's error state is correctly set.

Collapse
 
lizgarcia16 profile image
Laura Lizet Garcia Garcia

That's just what I don't know how to do, because I don't have the until it finishes loading,

  global.Image = class {
         builder() {
             this.onload= jest.fn();
             this.addEventListener = jest.fn()
             this.removeEventListener = jest.fn()
             setTimeout(() => {
                 this.onload();
             }, fifty);
         }
     };
Enter fullscreen mode Exit fullscreen mode

Add this in the beforeAll to simulate that the onload arrives but it still does not reach the handleLoad section

And this is my unit test:

   test("render AsyncImage", async () => {

        const logo = "./../../../assets/images/logo"

        let container
        await act(async () => {
            container = render(
                <Router>
                    <Provider store={store}>
                        <AsyncImage
                            src={logo}
                            alt="test.png"
                            className='img-fluid img-catalogCards'
                        />
                    </Provider>
                </Router>
            )
        })
    })
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
elliot_brenya profile image
Elliot Brenya sarfo

It sounds like you have set up a mock for the Image class to simulate the 'image' load event, but the component's 'handleLoad' function is still not being called. One thing you could try is to pass the 'onload' function directly as a prop to the component, so that it can be triggered manually in the test.

For example, you could update your component to accept an onLoad prop like this:

<AsyncImage
    src={logo}
    alt="test.png"
    className='img-fluid img-catalogCards'
    onLoad={handleLoad}
/>

Enter fullscreen mode Exit fullscreen mode

Then, in your test, you can trigger the 'handleLoad' function manually after the component has rendered:

const handleLoad = jest.fn();

let container;

beforeAll(() => {
  global.Image = class {
    constructor() {
      this.onload = jest.fn();
      this.addEventListener = jest.fn();
    }
  };
});

beforeEach(() => {
  act(() => {
    container = render(
      <Router>
        <Provider store={store}>
          <AsyncImage
            src={logo}
            alt="test.png"
            className="img-fluid img-catalogCards"
            onLoad={handleLoad}
          />
        </Provider>
      </Router>
    );
  });
});

test("render AsyncImage", () => {
  expect(handleLoad).toHaveBeenCalled();
  expect(global.Image.addEventListener.mock.calls.length).toBe(1);
  expect(global.Image.onload.mock.calls.length).toBe(1);
  const image = container.getByAltText("test.png");
  expect(image).toBeInTheDocument();
});

Enter fullscreen mode Exit fullscreen mode