How to preload images in React.js?

Supposing you have pictures: string[]; – array of pictures urls defined in your component’s props.
You should define componentDidMount() method in your component and then just create new Image object for each picture you want to be preloaded:

componentDidMount() {
    this.props.pictures.forEach((picture) => {
        const img = new Image();
        img.src = picture.fileName;
    });
}

It forces browser to load all images.

Leave a Comment