From 52710fbf982514ea6b70c8a041877c79e3b8fd25 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Thu, 2 Sep 2021 13:07:01 +0300 Subject: [PATCH] Add useIntersectionObserver --- snippets/useIntersectionObserver.md | 52 +++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 snippets/useIntersectionObserver.md diff --git a/snippets/useIntersectionObserver.md b/snippets/useIntersectionObserver.md new file mode 100644 index 000000000..789e6d3d5 --- /dev/null +++ b/snippets/useIntersectionObserver.md @@ -0,0 +1,52 @@ +--- +title: useIntersectionObserver +tags: hooks,state,effect,advanced +firstSeen: 2021-09-10T05:00:00-04:00 +--- + +Observes visibility changes for a given element. + +- Use the `useState()` hook to store the intersection value of the given element. +- Create an `IntersectionObserver()` with the given `options` and an appropriate callback to update the `isIntersecting` state variable. +- Use the `useEffect()` hook to call `IntersectionObserver.observe()` when mounting the component and clean up using `IntersectionObserver.unobserve()` when unmounting. + +```jsx +const useIntersectionObserver = (ref, options) => { + const [isIntersecting, setIsIntersecting] = React.useState(false); + + React.useEffect(() => { + const observer = new IntersectionObserver(([entry]) => { + setIsIntersecting(entry.isIntersecting); + }, options); + + if (ref.current) { + observer.observe(ref.current); + } + + return () => { + observer.unobserve(ref.current); + }; + }, []); + + return isIntersecting; +}; +``` + +```jsx +const MyApp = () => { + const ref = React.useRef(); + const onScreen = useIntersectionObserver(ref, { threshold: 0.5 }); + + return ( +
+
Scroll down
+
+

{onScreen ? 'Element is on screen.' : 'Scroll more!'}

+
+
+ ); +}; + +ReactDOM.render(, document.getElementById('root')); + +```