Comments 2
}, [ref.current, rootMargin])
Don't do this. Do not use ref
s 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.
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.
React Custom Hook: useOnScreen