Shadcn Hooks

useInViewport

A hook to check if an element is in the viewport

Loading...

Installation

npx shadcn@latest add @hooks/use-in-viewport
pnpm dlx shadcn@latest add @hooks/use-in-viewport
yarn dlx shadcn@latest add @hooks/use-in-viewport
bun x shadcn@latest add @hooks/use-in-viewport

Copy and paste the following code into your project.

create-effect-with-target.ts
import { isBrowser, isEqual, isFunction } from 'es-toolkit'
import { useRef } from 'react'
import { useUnmount } from '@/registry/hooks/use-unmount'
import type {
  DependencyList,
  EffectCallback,
  RefObject,
  useEffect,
  useLayoutEffect,
} from 'react'

type TargetValue<T> = T | undefined | null

type TargetType = HTMLElement | Element | Window | Document

export type BasicTarget<T extends TargetType = Element> =
  | (() => TargetValue<T>)
  | TargetValue<T>
  | RefObject<TargetValue<T>>

export function getTargetElement<T extends TargetType>(
  target: BasicTarget<T>,
  defaultElement?: T,
) {
  if (!isBrowser) {
    return undefined
  }

  if (!target) {
    return defaultElement
  }

  let targetElement: TargetValue<T>

  if (isFunction(target)) {
    targetElement = target()
  } else if ('current' in target) {
    targetElement = target.current
  } else {
    targetElement = target
  }

  return targetElement
}

export function createEffectWithTarget(
  useEffectType: typeof useEffect | typeof useLayoutEffect,
) {
  /**
   *
   * @param effect
   * @param deps
   * @param target target should compare ref.current vs ref.current, dom vs dom, ()=>dom vs ()=>dom
   */
  const useEffectWithTarget = (
    effect: EffectCallback,
    deps: DependencyList,
    target: BasicTarget<any> | BasicTarget<any>[],
  ) => {
    const hasInitRef = useRef(false)

    const lastElementRef = useRef<(Element | null)[]>([])
    const lastDepsRef = useRef<DependencyList>([])

    const unLoadRef = useRef<any>(undefined)

    useEffectType(() => {
      const targets = Array.isArray(target) ? target : [target]
      const els = targets.map((item) => getTargetElement(item))

      // init run
      if (!hasInitRef.current) {
        hasInitRef.current = true
        lastElementRef.current = els
        lastDepsRef.current = deps

        unLoadRef.current = effect()
        return
      }

      if (
        els.length !== lastElementRef.current.length ||
        !isEqual(lastElementRef.current, els) ||
        !isEqual(lastDepsRef.current, deps)
      ) {
        unLoadRef.current?.()

        lastElementRef.current = els
        lastDepsRef.current = deps
        unLoadRef.current = effect()
      }
    })

    useUnmount(() => {
      unLoadRef.current?.()
      // for react-refresh
      hasInitRef.current = false
    })
  }

  return useEffectWithTarget
}

use-effect-with-target.ts
import { useEffect } from 'react'
import { createEffectWithTarget } from '@/registry/lib/create-effect-with-target'

export const useEffectWithTarget = createEffectWithTarget(useEffect)

use-in-viewport.ts
import { useState } from 'react'
import { useEffectWithTarget } from '@/registry/hooks/use-effect-with-target'
import { getTargetElement } from '@/registry/lib/create-effect-with-target'
import type { BasicTarget } from '@/registry/lib/create-effect-with-target'

type CallbackType = (entry: IntersectionObserverEntry) => void

export interface Options {
  rootMargin?: string
  threshold?: number | number[]
  root?: BasicTarget<Element>
  callback?: CallbackType
}

export function useInViewport(
  target: BasicTarget | BasicTarget[],
  options?: Options,
) {
  const { callback, ...option } = options || {}

  const [state, setState] = useState<boolean>()
  const [ratio, setRatio] = useState<number>()

  useEffectWithTarget(
    () => {
      const targets = Array.isArray(target) ? target : [target]
      const els = targets
        .map((element) => getTargetElement(element))
        .filter(Boolean)

      if (!els.length) {
        return
      }

      const observer = new IntersectionObserver(
        (entries) => {
          for (const entry of entries) {
            setRatio(entry.intersectionRatio)
            setState(entry.isIntersecting)
            callback?.(entry)
          }
        },
        {
          ...option,
          root: getTargetElement(options?.root),
        },
      )

      els.forEach((el) => observer.observe(el!))

      return () => {
        observer.disconnect()
      }
    },
    [options?.rootMargin, options?.threshold, callback],
    target,
  )

  return [state, ratio] as const
}

API

/**
 * A hook to check if an element is in the viewport
 * @param target - The target to check if it is in the viewport
 * @param options - The options for the hook
 * @param options.rootMargin - The root margin for the intersection observer
 * @param options.threshold - The threshold for the intersection observer
 * @param options.root - The root element for the intersection observer
 * @param options.callback - The callback function to call when the target is in the viewport
 * @returns The boolean value indicating if the target is in the viewport and the ratio of the intersection
 */
export function useInViewport(
  target: BasicTarget | BasicTarget[],
  options?: Options,
): readonly [boolean | undefined, number | undefined]

Credits

Last updated on