Files
AndreaSlopFotografie/web/src/hooks/useInView.ts
T
SluijsensandClaude Opus 5.5 c1e90f0768 Moves the app to TanStack Start with prerendering
Every page is now built as HTML from sitePages.ts, with a catch-all route for
404.html. Hooks that read the browser during render are safe for prerendering.
The script step that keeps the CSP intact follows, so this build still has
inline scripts and is not deployable yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 17:58:54 +01:00

49 lines
1.6 KiB
TypeScript

import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
const noopSubscribe = () => () => {};
type UseInViewOptions = {
threshold?: number;
rootMargin?: string;
// Skip observing and report "in view" right away
skip?: boolean;
};
// Tells whether an element has come into (or near) the viewport, once.
// Without IntersectionObserver the element counts as in view (from the first
// render after hydration), so content is never left hidden or unloaded.
export default function useInView<T extends Element>({
threshold = 0,
rootMargin = '0px',
skip = false,
}: UseInViewOptions = {}) {
const ref = useRef<T>(null);
// The server cannot know, so prerender and hydration both assume support
const unsupported = useSyncExternalStore(
noopSubscribe,
() => typeof IntersectionObserver === 'undefined',
() => false,
);
const [intersected, setIntersected] = useState(false);
useEffect(() => {
const element = ref.current;
if (!element || skip || unsupported || intersected) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting)) {
setIntersected(true);
observer.disconnect();
}
},
{ threshold, rootMargin },
);
observer.observe(element);
return () => observer.disconnect();
}, [skip, unsupported, intersected, threshold, rootMargin]);
return { ref, inView: skip || intersected || unsupported };
}