useIntersectionObserver
useIntersectionObserver
allows you to observe when an element enters or exits the viewport. This can be useful for lazy-loading images, infinite scrolling, or triggering animations when an element becomes visible.
Usage
-
Make sure you have
@ridgehkr/useful
installed in your application. If not, you can get started by following the installation instructions. -
Import
useIntersectionObserver
into your component.
import { useIntersectionObserver } from '@ridgehkr/useful'
Example
In the following example, useIntersectionObserver
is used to lazy-load a set of images, only rendering images that are currently in the viewport.
import { useIntersectionObserver } from '@ridgehkr/useful'
type FigureProps = {
src: string
caption: string
}
const images = [
{
src: 'https://picsum.photos/1000/500',
caption: 'First Image',
},
{
src: 'https://picsum.photos/1000/620',
caption: 'Second Image',
},
{
src: 'https://picsum.photos/1000/750',
caption: 'Third Image',
},
{
src: 'https://picsum.photos/1000/800',
caption: 'Fourth Image',
},
{
src: 'https://picsum.photos/1000/400',
caption: 'Fifth Image',
},
{
src: 'https://picsum.photos/1100/500',
caption: 'Sixth Image',
},
{
src: 'https://picsum.photos/1000/560',
caption: 'Seventh Image',
},
]
const Figure = ({ src, caption }: FigureProps) => {
const { ref, entry } = useIntersectionObserver({
threshold: 0,
root: null,
rootMargin: '0px',
})
return (
<article>
<figure ref={ref}>
{entry?.isIntersecting && (
<>
<img src={src} alt='Lazy-loaded image' />
<figcaption>{caption}</figcaption>
</>
)}
</figure>
</article>
)
}
function LazyLoader() {
return (
<div>
{images.map(({ src, caption }, index) => {
return <Figure key={index} src={src} caption={caption} />
})}
</div>
)
}
API
Hook Signature
useIntersectionObserver(options: IntersectionObserverOptions): IntersectionObserverState
Parameters
The IntersectionObserverOptions
are passed directly into the IntersectionObserver
constructor. You can read the full documentation for these options on MDN (opens in a new tab).
Return Value
useIntersectionObserver
returns an IntersectionObserverState
object containing the following properties:
Property | Type | Description |
---|---|---|
ref | React ref (opens in a new tab) | A React ref that should be assigned to the element you want to observe. |
entry | IntersectionObserverEntry (opens in a new tab) | An instance of IntersectionObserverEntry containing information about the intersection of the observed element. |