React Suspense와 Image loading

이현석·2022년 12월 23일
1

프로젝트를 진행하면서 react-query와 suspense에 대한 만족도가 아주 높았다.
그런데 화면에서 아주 거슬리는 것이 있었는데 이미지 로딩 문제였다.
이미지 로딩을 처리하는 여러가지 방법이 있었지만 suspense를 이용하여 처리하면 좋겠다라는 생각이 들었다.
먼저 이미지를 로드하는 코드를 작성했다.

const loadImage = (src: string) =>
  new Promise((resolve, reject) => {
    const img = new Image();
    img.src = src;

    img.onload = () => {
      resolve(img);
    };
    img.onerror = (e) => {
      reject(e);
    };
  });

위 함수를 실행하여 받은 promise가 fulfilled 되고난 후 이미지 렌더링을 시도하면 이미지가 preload된 효과를 얻을 수 있다. promise 기반의 이미지 로드 함수 구현이 완료 되었으니 이제 suspense와 연결만 하면 된다!

하지만 내 생각처럼 쉽게 되지는 않았고 나만 눈감고 넘어가면 되는데 괜히 고생하는 거 아닌가 싶은 생각이 들었다.
그러던 중 문득 비동기 작업을 처리 할 수 있는 react-query가 스쳐갔다.

export const usePreloadImages = (urls: string[]) => {
  useQuery(preloadImageKeys.urls(urls), () =>
    Promise.all(urls.map(preloadImage)),
  );
};

const NeedPreloadImagesComponent = ()=>{
  usePreloadImages(["images/star.png","images/bg.png", ...])
//생략
}
     
const App = ()=>{
    <Suspense fallback={<Loading/>}>
    	<NeedPreloadImagesComponent />
    </Suspense>
  }
                   

위와 같이 코드를 작성하면 NeedPreloadImagesComponent에서 이미지를 미리 로드 되는 동안 컴포넌트를 보여주게 된다.

profile
안녕하세요

0개의 댓글