Use In View
dashboardblocks/use-in-viewFreeHook
A hook that tracks whether an element is visible in the viewport using IntersectionObserver.
Install it
npx shadcn@latest add https://dashboardblocks.com/r/use-in-view.jsonSource
1'use client'23import { useLayoutEffect, useRef, useState } from 'react'45interface UseInViewOptions {6 /**7 * Intersection Observer threshold (0-1)8 * @default 1.09 */10 threshold?: number11 /**12 * Intersection Observer root margin13 * @default '0px'14 */15 rootMargin?: string16}1718/**19 * A hook that tracks whether an element is visible in the viewport using IntersectionObserver.20 * @returns An object containing a ref to attach to the element and an isInView boolean state.21 */22export function useInView(options: UseInViewOptions = {}) {23 const { rootMargin = '0px', threshold = 1.0 } = options2425 const ref = useRef<HTMLElement | null>(null)26 const [isInView, setIsInView] = useState(false)2728 useLayoutEffect(() => {29 const element = ref.current30 if (!element) return3132 const observer = new IntersectionObserver(33 ([entry]) => {34 setIsInView(entry.isIntersecting)35 },36 { threshold, rootMargin },37 )3839 observer.observe(element)4041 return () => {42 observer.disconnect()43 }44 }, [rootMargin, threshold])4546 return {47 isInView,48 ref,49 }50}
Files it writes
More from dashboardblocks
All 36 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| Use Animated Numberuse-animated-number | dashboardblocks | Hooks | Free | no deps |
