Overview
TheuseIntersectionObserver hook provides a simple way to detect when an element enters or exits the viewport. This is useful for implementing lazy loading, infinite scroll, animations on scroll, and other viewport-based interactions.
Function Signature
Parameters
Configuration options for the Intersection Observer. The hook provides sensible defaults but allows full customization.Default values:
root:null(uses viewport)rootMargin:'400px'(triggers 400px before element enters viewport)threshold:0.1(triggers when 10% of element is visible)
IntersectionObserverInit Properties
The element used as the viewport for checking visibility. Defaults to the browser viewport if
null.Margin around the root element. Can be used to grow or shrink the intersection area. Accepts CSS-like values (e.g.,
"10px", "10px 20px").A single number or array of numbers between 0 and 1, indicating at what percentage of the target’s visibility the observer’s callback should execute.
Return Values
A React ref object that should be attached to the element you want to observe. The hook monitors this element’s visibility.
A boolean indicating whether the observed element is currently intersecting with the viewport (or root element). Updates automatically as the element enters or exits the viewport.
Usage Example
Here’s a real-world example from the Bookmark component (/home/daytona/workspace/source/src/components/Bookmark.tsx:16) implementing lazy loading:Custom Options Example
Implementation Details
The hook:- Creates an
IntersectionObserverinstance with merged default and custom options - Observes the element referenced by the returned
ref - Updates the
isVisiblestate when the element’s intersection status changes - Automatically cleans up the observer when the component unmounts
- Re-creates the observer if options change
Common Use Cases
- Lazy loading images: Load images only when they’re about to enter the viewport
- Infinite scroll: Load more content when user scrolls near the bottom
- Animations on scroll: Trigger animations when elements become visible
- Analytics: Track when users view specific sections
- Performance optimization: Defer rendering of expensive components
Performance Considerations
The default
rootMargin of '400px' means elements will be considered visible 400px before they enter the viewport. This provides a buffer for lazy loading, ensuring images load before users see them.