useOnScreen: memoize IntersectionObserver, fix types

This commit is contained in:
Alex Gleason 2023-02-06 15:39:17 -06:00
parent 76c76688e9
commit cb74b0a37c
No known key found for this signature in database
GPG key ID: 7211D1F99744FBB7

View file

@ -1,13 +1,17 @@
import React from 'react';
import React, { useEffect, useMemo, useState } from 'react';
export const useOnScreen = (ref: React.MutableRefObject<HTMLElement>) => {
const [isIntersecting, setIntersecting] = React.useState(false);
/** Detect whether a given element is on the screen. */
// https://stackoverflow.com/a/64892655
export const useOnScreen = <T>(ref: React.RefObject<T & Element>) => {
const [isIntersecting, setIntersecting] = useState(false);
const observer = new IntersectionObserver(
([entry]) => setIntersecting(entry.isIntersecting),
);
const observer = useMemo(() => {
return new IntersectionObserver(
([entry]) => setIntersecting(entry.isIntersecting),
);
}, []);
React.useEffect(() => {
useEffect(() => {
if (ref.current) {
observer.observe(ref.current);
}