Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | 486x 486x 486x 245x 245x 244x 239x 239x 5x 2x 2x 2x 5x 5x 486x 977x | import { useEffect, useRef, useState } from "react";
/**
* True once the element has scrolled into view, and stays true.
*
* Six marketing pages declared this hook verbatim (only the default
* `threshold` differed, 0.1 vs 0.15). It observes once and unobserves on the
* first intersection, because a reveal animation is a one-shot entrance —
* re-hiding content when it scrolls back out would be worse than not
* animating at all.
*
* ```tsx
* const { ref, visible } = useReveal();
* <div ref={ref} style={{ opacity: visible ? 1 : 0 }} />
* ```
*
* Prefer the {@link Reveal} component; reach for the hook directly only when
* the animation is not a simple fade-and-rise.
*/
export interface RevealState {
ref: React.RefObject<HTMLDivElement>;
visible: boolean;
}
export function useReveal(threshold = 0.1): RevealState {
const ref = useRef<HTMLDivElement>(null);
// Start visible when the viewer has asked for reduced motion: there is no
// entrance to play, and content must never depend on an animation running.
const [visible, setVisible] = useState(() => prefersReducedMotion());
useEffect(() => {
const el = ref.current;
if (!el || prefersReducedMotion()) return;
// jsdom and older browsers have no IntersectionObserver. Without this the
// content would stay at opacity 0 forever — invisible, not just unanimated.
if (typeof IntersectionObserver === "undefined") {
setVisible(true);
return;
}
const observer = new IntersectionObserver(
([entry]) => {
Eif (entry.isIntersecting) {
setVisible(true);
observer.unobserve(el);
}
},
{ threshold },
);
observer.observe(el);
return () => observer.disconnect();
}, [threshold]);
return { ref, visible };
}
/** Whether the viewer has asked the OS to minimise animation. */
export function prefersReducedMotion(): boolean {
return (
typeof window !== "undefined" &&
typeof window.matchMedia === "function" &&
window.matchMedia("(prefers-reduced-motion: reduce)").matches
);
}
export default useReveal;
|