diff --git a/components/RUA/RUACodeSandbox.tsx b/components/RUA/RUACodeSandbox.tsx index 61591fe..188b413 100644 --- a/components/RUA/RUACodeSandbox.tsx +++ b/components/RUA/RUACodeSandbox.tsx @@ -21,8 +21,7 @@ const RUACodeSandbox = ({ url }: Props) => { const currentTheme = theme === 'system' ? systemTheme : theme ?? 'light'; const { ref, inView } = useInView(); - const sandUrl = new URL(url); - const embed = sandUrl.pathname.split('/')[2]; + const embed = new URL(url).pathname.split('/')[2]; const [src, setSrc] = useState(''); useEffect(() => { inView && diff --git a/lib/hooks/useInView.ts b/lib/hooks/useInView.ts index ad4ca33..74baf2d 100644 --- a/lib/hooks/useInView.ts +++ b/lib/hooks/useInView.ts @@ -1,23 +1,26 @@ -import { useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from 'react'; const useInView = () => { const ref = useRef(null); const [inView, setInView] = useState(false); - useEffect(() => { - const observer = new IntersectionObserver((entries, observer) => { + const observeCallback: IntersectionObserverCallback = useCallback( + (entries, observer) => { entries.forEach((entry) => { - if (entry.isIntersecting) { - if (ref.current) { - setInView(true); - observer.unobserve(ref.current); - } - } + if (!entry.isIntersecting) return; + if (!ref.current) return; + setInView(true); + observer.unobserve(ref.current); }); - }); + }, + [] + ); + + useEffect(() => { + const observer = new IntersectionObserver(observeCallback); ref.current && observer.observe(ref.current); - }, []); + }, [observeCallback]); return { ref, inView }; };