From da3346f52aa8a61c3ae4b78a0c30b7f4404ddd05 Mon Sep 17 00:00:00 2001 From: yurikochergin Date: Fri, 8 Nov 2024 11:56:01 +0300 Subject: [PATCH] feat(use-is-visible): added "once" option --- .size-limit.json | 2 +- packages/use-is-visible/index.ts | 9 ++++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/.size-limit.json b/.size-limit.json index cb5ef46..1909cde 100644 --- a/.size-limit.json +++ b/.size-limit.json @@ -49,7 +49,7 @@ }, { "path": "packages/use-is-visible/dist/index.js", - "limit": "3.08 KB" + "limit": "3.1 KB" }, { "path": "packages/use-transition-visible/dist/index.js", diff --git a/packages/use-is-visible/index.ts b/packages/use-is-visible/index.ts index e047ec7..373d036 100644 --- a/packages/use-is-visible/index.ts +++ b/packages/use-is-visible/index.ts @@ -4,7 +4,10 @@ import {useEffect, useState} from 'react' /** Tracks the intersection of an element with its parent or document's viewport. */ export function useIsVisible( element: Element, - options: IntersectionObserverInit = {threshold: 1} + options: IntersectionObserverInit & {once: boolean} = { + threshold: 1, + once: false + } ): boolean { const [isVisible, setIsVisible] = useState(false) @@ -23,6 +26,10 @@ export function useIsVisible( thresholds.some((threshold) => entry.intersectionRatio >= threshold) setIsVisible(isIntersecting) + + if (isIntersecting && options.once) { + observer.disconnect() + } }) }, options