https://github.com/thebuilder/react-intersection-observer#readme
React implementation of the Intersection Observer API to tell you when an element enters or leaves the viewport. Contains both a Hooks, render props and plain children implementation.
Storybook Demo: https://react-intersection-observer.vercel.app
Features
- 🪝 Hooks or Component API - With useInView it's easier than ever to monitor elements
- ⚡️ Optimized performance - Reuses Intersection Observer instances where possible
- ⚙️ Matches native API - Intuitive to use
- 🛠 Written in TypeScript - It'll fit right into your existing TypeScript project
- 🧪 Ready to test - Mocks the Intersection Observer for easy testing with Jest or Vitest
- 🌳 Tree-shakeable - Only include the parts you use
- 💥 Tiny bundle - Around ~1.15kB for useInView and ~1.6kB for <InView>
Installation
Install using Yarn:
yarn add react-intersection-observer
or NPM:
npm install react-intersection-observer --save
사용 예제
import { useInView } from 'react-intersection-observer';
const { ref, inView } = useInView({
threshold: 0,
});
useEffect(() => {
setPosts([]);
}, [location.pathname]);
useEffect(() => {
if (inView && !loading) {
const start_author = posts.length ? posts[posts.length - 1].author : null;
const start_permlink = posts.length ? posts[posts.length - 1].permlink : null;
setPage({ start_author: start_author, start_permlink: start_permlink });
}
}, [inView]);
useEffect(() => {
getPosts();
}, [page]);
...
<div ref={ref} className="mt-10 ml-10 h-screen"></div>
스크롤시 데이터 로딩하기
react에서 스크롤시 데이터를 로드하기 좋은 방법 입니다.
위 라이브러리는 1.88kb의 작은 사이즈로 사용하는데 로딩 속도에 대한 부담이 적습니다.
ref가 보여지면 inview가 true로 변경이되고,
이신호를 받아서 데이터를 로드하는 로직 입니다.
위코드는 https://delog.io 에 적용되어 있습니다.
'Program > React' 카테고리의 다른 글
[next.js] version 13, head.js (1) | 2023.01.06 |
---|---|
[next.js] version 13, head.js (1) | 2023.01.02 |
[next.js]An error occurred in the Server Components render. (0) | 2023.01.02 |
yarn create next-app --typescript , antd (0) | 2022.07.07 |
Typescript + Router (0) | 2022.07.05 |
댓글