#16PerformanceMedium

Import On Visibility (IntersectionObserver + React.lazy)

Import On Visibility — IntersectionObserver + React.lazy

무거운 Chart 모듈을 요소가 화면에 들어오는 순간까지 import 하지 않도록 분리하세요. 긴 페이지나 무한 스크롤 카드 리스트에서 흔히 쓰는 패턴입니다.

요구사항

  1. LazyChart 컴포넌트는 초기에 placeholder만 렌더
  2. IntersectionObserver 로 자신이 뷰포트에 들어오는지 감지
  3. 뷰포트에 진입한 순간에만 Chart 모듈을 lazy import 하고 Suspense 로 감싸 렌더
  4. 한 번 로드된 후에는 다시 뷰포트 밖으로 나가도 계속 렌더 유지 (one-shot — observer는 disconnect)
  5. 초기 렌더 시점에는 Chart 모듈이 fetch/evaluate 되지 않아야 함

힌트

  • const Chart = lazy(() => import('./Chart'))
  • useEffect 안에서 new IntersectionObserver(callback) 생성 → observer.observe(ref.current)
  • callback에서 entry.isIntersecting 이 true가 되면 setVisible(true) + observer.disconnect()
  • 컴포넌트 unmount 시 cleanup으로 observer.disconnect()

학습 포인트

  • IntersectionObserver 의 실제 사용 — viewport-driven lazy loading의 표준 API
  • React에서 ref + useEffect + observer 통합 패턴
  • one-shot 트리거 (관찰 끝나면 disconnect)
Sandpack 로드 중…