-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add hook interception observer and update lazy image (#154)
* Add hook interception observer and update lazy image * Fix import css --------- Co-authored-by: Hugo <[email protected]> Co-authored-by: Willy Brauner <[email protected]>
- Loading branch information
1 parent
fbac0f1
commit 0d8d88e
Showing
3 changed files
with
82 additions
and
37 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import { RefObject, useEffect, useState } from "react" | ||
|
||
export interface Args extends IntersectionObserverInit { | ||
freezeOnceVisible?: boolean | ||
} | ||
|
||
/** | ||
* useIntersectionObserver | ||
* https://usehooks-ts.com/react-hook/use-intersection-observer | ||
* | ||
* @param elementRef | ||
* @param threshold | ||
* @param root | ||
* @param rootMargin | ||
* @param freezeOnceVisible | ||
*/ | ||
function useIntersectionObserver( | ||
elementRef: RefObject<Element>, | ||
{ threshold = 0, root = null, rootMargin = "0%", freezeOnceVisible = false }: Args | ||
): IntersectionObserverEntry | undefined { | ||
const [entry, setEntry] = useState<IntersectionObserverEntry>() | ||
|
||
const frozen = entry?.isIntersecting && freezeOnceVisible | ||
|
||
const updateEntry = ([entry]: IntersectionObserverEntry[]): void => { | ||
setEntry(entry) | ||
} | ||
useEffect(() => { | ||
const node = elementRef?.current // DOM Ref | ||
const hasIOSupport = !!window.IntersectionObserver | ||
|
||
if (!hasIOSupport || frozen || !node) return | ||
|
||
const observerParams = { threshold, root, rootMargin } | ||
const observer = new IntersectionObserver(updateEntry, observerParams) | ||
observer.observe(node) | ||
|
||
return () => observer.disconnect() | ||
}, [elementRef, JSON.stringify(threshold), root, rootMargin, frozen]) | ||
|
||
return entry | ||
} | ||
|
||
export default useIntersectionObserver |