{"id":14276,"url":"\/distributions\/14276\/click?bit=1&hash=721b78297d313f451e61a17537482715c74771bae8c8ce438ed30c5ac3bb4196","title":"\u0418\u043d\u0432\u0435\u0441\u0442\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0432 \u043b\u044e\u0431\u043e\u0439 \u0442\u043e\u0432\u0430\u0440 \u0438\u043b\u0438 \u0443\u0441\u043b\u0443\u0433\u0443 \u0431\u0435\u0437 \u0431\u0438\u0440\u0436\u0438","buttonText":"","imageUuid":""}

React Custom Hook: useOnScreen

React Custom Hook: useOnScreen

In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the "useOnScreen" hook, one of the many carefully crafted hooks available in the collection of React custom hooks.

import { useEffect, useState } from "react" export default function useOnScreen(ref, rootMargin = "0px") { const [isVisible, setIsVisible] = useState(false) useEffect(() => { if (ref.current == null) return const observer = new IntersectionObserver( ([entry]) => setIsVisible(entry.isIntersecting), { rootMargin } ) observer.observe(ref.current) return () => { if (ref.current == null) return observer.unobserve(ref.current) } }, [ref.current, rootMargin]) return isVisible }

The useOnScreen hook leverages the power of the Intersection Observer API, making it efficient and reliable. By simply providing a ref to the element you want to monitor, useOnScreen will notify you when it enters or exits the viewport.

One of the key advantages of useOnScreen is its simplicity. With just a few lines of code, you can detect if an element is visible and respond accordingly. This can be immensely useful in scenarios where you want to trigger animations, lazy load images, or load additional content as the user scrolls.

To use this hook, first import it into your component file. Then, create a ref using the useRef hook to target the desired element. Pass the ref as the first argument to the useOnScreen hook, and you're all set! You can also provide an optional rootMargin value to adjust the visible threshold.

import { useRef } from "react" import useOnScreen from "./useOnScreen" export default function OnScreenComponentComponent() { const headerTwoRef = useRef() const visible = useOnScreen(headerTwoRef, "-100px") return ( <div> <h1>Header</h1> <div> ... </div> <h1 ref={headerTwoRef}>Header 2 {visible && "(Visible)"}</h1> <div> ... </div> </div> ) }

In our example code, the OnScreenComponentComponent demonstrates how to use the useOnScreen hook. By attaching the ref to the second header element, we can display a "(Visible)" text when it enters the viewport. Feel free to customize the logic within your component to suit your specific needs.

0
Комментарии
-3 комментариев
Раскрывать всегда