-
Notifications
You must be signed in to change notification settings - Fork 0
[URH-12] useIntersectionObserver 신규 #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
…ct/use-react-hooks into feature/use-intersection-observer
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
작성해주신 훅 잘 보았습니다. 실제로 사용해보면 더 이해가 잘 될 것 같은데, 전체적인 예시 코드를 작성해주실 수 있을까요?
해당 훅을 사용하기 위해서
<div ref={intersectionRef}> </div>
entry의 경우, 그외 변수
onChange 대표적인 활용 예시대표적인 활용 예시로는 다음과 같이 Lazy Loading을 수행할 수 있습니다
const Temp = () => {
const nextItemRef = useRef(1);
const [items, setItems] = useState<number[]>([]);
const [loading, setLoading] = useState(false);
const fetchItems = async () => {
return new Promise<number[]>((resolve) => {
setTimeout(() => {
const newItems = [
nextItemRef.current,
nextItemRef.current + 1,
nextItemRef.current + 2,
];
nextItemRef.current += 3;
resolve(newItems);
}, 1000);
});
};
const handleIntersectionChange = async (isView: boolean) => {
if (isView && !loading) {
setLoading(true);
try {
const newItems = await fetchItems();
setItems((prevItems) => [...prevItems, ...newItems]);
setLoading(false);
} catch (error) {
console.error(error);
setLoading(false);
}
}
};
const { intersectionRef } = useIntersectionObserver({
threshold: 0.5,
onChange: handleIntersectionChange,
});
return (
<div>
<div style={{ height: "1000px" }}></div>
<div
style={{
padding: "30px",
backgroundColor: "lightblue",
}}
>
{items.map((item, index) => (
<div
key={index}
style={{
margin: "10px",
height: "20px",
backgroundColor: "lightyellow",
padding: "10px",
}}
>
Item {item}
</div>
))}
{loading && <p>Loading more items...</p>}
</div>
<div ref={intersectionRef}> </div>
</div>
);
};
export default Temp; 2024-07-17.194139.mp4onEnter, onLeave
const handleIntersectionChange = async () => {
if (!loading) {
setLoading(true);
try {
const newItems = await fetchItems();
setItems((prevItems) => [...prevItems, ...newItems]);
setLoading(false);
} catch (error) {
console.error(error);
setLoading(false);
}
}
};
const { intersectionRef, isView, entry } = useIntersectionObserver({
onEnter: handleIntersectionChange,
}); 필요에 따라 이와 같이 isView를 제외하고 위 3가지 콜백함수를 비교하면 다음과 같습니다 const { intersectionRef } = useIntersectionObserver({
onChange() {
console.log("CHANGE");
},
onEnter() {
console.log("ENTER");
},
onLeave() {
console.log("LEAVE");
},
}); 2024-07-17.202535.mp4 |
상세한 설명 감사합니다 😊 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🤩
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
고생하셨습니다! 🚀
👾 Pull Request
1️⃣ Spec
2️⃣ 변경 사항
3️⃣ 예시 코드
1. 기본
intersectionRef
: 훅에서 사용할 요소의 상태를 설정하는 데 사용되는 디스패치 함수. 감지하고자 하는 요소에 설정isView
: 요소가 현재 뷰포트 내에 보이는지 여부를 나타내는 상태 값entry
: Intersection Observer API를 사용하여 요소의 교차 상태와 관련된 정보를 나타내는 객체2. IntersectionObserver API 기본 옵션
root
: 뷰포트 대신 사용할 요소 객체 지정. 기본적으로 브라우저의 Viewport가 사용됨(null)rootMargin
: Root의 범위를 확장하거나 축소시킴threshold
: observer가 실행되기 위한 최소한의 타켓의 가시성 비율3. 부가옵션
initialView
: 초기 감지값visibleOnce
: 처음 한번만 감지4. callback 함수
onChange
: 타겟 엘리먼트의 가시성 상태가 변경될 때 호출할 콜백 함수onEnter
: 타겟 엘리먼트가 화면에 나타날 때 호출할 콜백 함수onLeave
: 타겟 엘리먼트가 화면에서 사라질 때 호출할 콜백 함수4️⃣ 관련 문서 (선택 사항)