Skip to content

Instantly share code, notes, and snippets.

@chrisciampoli
Created October 18, 2023 14:07
Show Gist options
  • Save chrisciampoli/bd1f846217172cbea7ea12252f8a8afe to your computer and use it in GitHub Desktop.
Save chrisciampoli/bd1f846217172cbea7ea12252f8a8afe to your computer and use it in GitHub Desktop.
useObserver Custom React Hook
import React from 'react';
import { useIntersectionObserver } from './useIntersectionObserver'; // Import your custom hook
function MyComponent() {
const { observedRef, inView } = useIntersectionObserver();
return (
<div
className={`flex-1 parent-flex flex ${inView ? 'group inview' : ''}`}
ref={observedRef}
>
{/* Your component content */}
</div>
);
}
'use client';
import { ReactNode, useEffect, useRef, useState } from 'react';
export default function Observer({
children,
className,
key,
repeat = false,
}: {
children: ReactNode;
className?: string;
key?: string;
repeat?: boolean;
}) {
const [inView, setInView] = useState<boolean>(false);
const observed = useRef(null);
const [once, setOnce] = useState<boolean>(false);
useEffect(() => {
const reff = observed;
const observer = new IntersectionObserver(
(e) => {
if (observed.current) {
setInView(() => e[0].isIntersecting);
if (e[0].isIntersecting) {
setOnce(() => true);
}
}
},
{ threshold: 0.6 }
);
if (reff.current) {
observer.observe(reff.current);
}
return () => {
if (reff.current) {
observer.unobserve(reff.current);
}
};
}, []);
return (
<div
key={key}
className={`flex-1 parent-flex flex ${className ? className : ''} ${
inView || (once && !repeat) ? 'group inview' : ''
}`}
ref={observed}
>
{children}
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment