Skip to content

Commit

Permalink
chore: pull useIsStuck
Browse files Browse the repository at this point in the history
  • Loading branch information
dominik-stumpf committed Jul 10, 2024
1 parent 900718f commit 77e8551
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions src/hooks/useIsStuck.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,32 @@
import { useRouter } from "next/router"
import { useEffect, useRef, useState } from "react"
import {
Dispatch,
MutableRefObject,
SetStateAction,
useEffect,
useRef,
useState,
} from "react"

/**
* The IntersectionObserver triggers if the element is off the viewport, so we have
* to set top="-1px" or bottom="-1px" on the sticky element instead of 0
*/
const useIsStuck = () => {
const useIsStuck = (
setIsStuck?: Dispatch<SetStateAction<boolean>>
): { ref: MutableRefObject<null>; isStuck?: boolean } => {
const ref = useRef(null)
const [isStuck, setIsStuck] = useState(false)
const { isReady } = useRouter()
const [isStuck, setIsStuckLocal] = useState(false)
const setIsStuckActive = setIsStuck ?? setIsStuckLocal

useEffect(() => {
if (!ref.current) return
const cachedRef = ref.current
const topOffsetPx = parseInt(getComputedStyle(cachedRef).top) + 1
const bottomOffsetPx = parseInt(getComputedStyle(cachedRef).bottom) + 1

const observer = new IntersectionObserver(
([e]) => {
setIsStuck(
setIsStuckActive(
!e.isIntersecting &&
(e.boundingClientRect.top < topOffsetPx ||
e.boundingClientRect.bottom > bottomOffsetPx)
Expand All @@ -30,9 +39,9 @@ const useIsStuck = () => {
)
observer.observe(cachedRef)
return () => observer.unobserve(cachedRef)
}, [ref, isReady])
}, [ref])

return { ref, isStuck }
return { ref, isStuck: setIsStuck ? undefined : isStuck }
}

export default useIsStuck

0 comments on commit 77e8551

Please sign in to comment.