Search code examples
javascriptreactjsimageapioptimization

Optimization of loading images in the React application


I use the Unsplash API to search for images, and then output these images to div blocks. But there was such a problem - VERY slow and delayed loading of images. How can this be optimized or slightly speed up the loading of images?

import './App.css';
import { useState, React } from 'react';

function App() {
  const [search, setSearch] = useState('');
  const [containerImgs, setContainerImgs] = useState([]);

  const searchInput = event => {
    setSearch(event.target.value);
  }

  async function getPhotos() {
    let response = await fetch("https://api.unsplash.com/search/photos?page=1&query="+search+"&client_id={APP-SECRET}", {
      
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });
  
    let result = await response.json();
    if (result) {
      setContainerImgs(result.results);
      console.log(result.results)
    }
  }

  return (
    <div className="container">
      <input type="text" onChange={searchInput} />
      <input type="button" value="Go" onClick={getPhotos}/>
      <div className="images-container">
          {containerImgs.map(item =>
                <div key={item.id} className="card">
                  <img src={item.urls.full} content='fdsfsd' alt={item.alt_description}/>
                  <div className='user-info'>{item.user.name}</div>
                </div>
            ) }
      </div>
    </div>
  );
}

export default App;


Solution

  • So, I figured out how to quickly load an image - there are several types of images with different resolutions in the Unsplash API I had a long loading of photo cards, because I upload the largest size of the picture I set a smaller image upload size in the API and everything became much better