useInViewport
A custom React hook that detects if an element is in the viewport.
useInViewport
is a custom React hook that detects when an element is in the viewport. It accepts a ref object pointing to the element you want to monitor and returns a boolean indicating the visibility state. This is useful for creating lazy-loaded components or triggering animations when an element comes into view.
Example
Loading...
Install
npx shadcn@latest add https://unlogg.com/r/use-in-viewport.json
pnpm dlx shadcn@latest add https://unlogg.com/r/use-in-viewport.json
bunx shadcn@latest add https://unlogg.com/r/use-in-viewport.json
Notes
- Returns an object with a callback
ref
to attach to the element you want to observe. - Returns a boolean
inView
indicating if the element is currently in the viewport. - Uses the Intersection Observer API under the hood.
API Reference
Parameters
Prop | Type | Default |
---|
Returns
Prop | Type | Default |
---|---|---|
inView? | boolean | - |
ref? | React.RefCallback<T | null> | - |
Usage
import { useInViewport } from "@/hooks/use-in-viewport";
function InViewportComponent() {
const { ref, inView } = useInViewport<HTMLDivElement>();
return (
<div
ref={ref}
className={inView ? "bg-green-100" : "bg-gray-100"}
>
{inView ? "In viewport!" : "Out of viewport"}
</div>
);
}
Use Cases
- Lazy Loading: Load images or components only when they enter the viewport
- Animations: Trigger animations when elements scroll into view
- Infinite Scroll: Detect when the user reaches the end of a list
- Analytics: Track when elements are actually viewed by users
- Sticky Headers: Activate sticky headers when they enter/leave the viewport
- Progress Indicators: Show progress as sections enter the viewport
- Ad Visibility: Measure ad impressions based on viewport entry
- Reveal Effects: Gradually reveal content as it scrolls into view
- Button States: Create enhanced button hover states
- Image Overlays: Show overlays when images are hovered
- Navigation Items: Highlight navigation items on hover
- Form Field Enhancement: Show additional information on form field hover
- Data Visualization: Highlight chart elements on hover
- Progressive Disclosure: Reveal additional content on hover