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.

Github: https://github.com/sergeyleschev/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.

Full Version | React Custom Hooks: https://habr.com/en/articles/746760/

@Leschev
20.09.2023 09:21 UTC
Первоисточник

Комментарии

@faiwer
20.09.2023 18:32 UTC
+1
}, [ref.current, rootMargin])

Don't do this. Do not use refs as reactive elements (in this case in dependencies). Because refs are not reactive. Once something sets ref.current = ... it won't rerender the component, thus it won't retrigger the effect. So the proper version of the hook should take the DOM Element directly.

@bitcot
19.10.2023 09:13 UTC
0

The useOnScreen custom hook is a React hook that allows you to detect whether or not an element is currently visible on the screen. This can be useful for a variety of purposes, such as lazy loading images, triggering animations, or loading additional content as the user scrolls.

The useOnScreen hook works by using the Intersection Observer API. The Intersection Observer API is a modern JavaScript feature that allows you to monitor changes in the visibility of elements. The useOnScreen hook abstracts away the complexity of using the Intersection Observer API, making it easy to use in your React components.

To use the useOnScreen hook, first import it into your component file. Then, create a ref for the element that you want to monitor. Pass the ref to the useOnScreen hook as an argument. The useOnScreen hook will return a boolean value that indicates whether or not the element is currently visible on the screen.

Here is an example of how to use the useOnScreen hook:

JavaScript

import React, { useRef, useState } from 'react';
import useOnScreen from './useOnScreen';
const MyComponent = () => {
const ref = useRef(null);
const isVisible = useOnScreen(ref);
const [imageSrc, setImageSrc] = useState('');
// Lazy load the image if it is visible on the screen.
if (isVisible) {
setImageSrc('https://example.com/image.jpg');
}
return (
<div>
<img src={imageSrc} alt="My image" ref={ref} />
</div>
);
};
export default MyComponent;

Use code with caution. Learn more

content_copy

In this example, the useOnScreen hook is used to lazy load an image. The image will only be loaded if it is currently visible on the screen. This can help to improve the performance of your app by reducing the amount of data that needs to be loaded.

The useOnScreen hook can also be used to trigger animations or load additional content as the user scrolls. For example, you could use the useOnScreen hook to trigger an animation when an element enters the viewport. You could also use the useOnScreen hook to load additional content as the user scrolls down the page.

The useOnScreen hook is a powerful tool that can be used to improve the performance and user experience of your React apps.