diff --git a/components/RUA/RUASandpack.tsx b/components/RUA/RUASandpack.tsx index aeb80d9..8d28024 100644 --- a/components/RUA/RUASandpack.tsx +++ b/components/RUA/RUASandpack.tsx @@ -2,25 +2,25 @@ import { FC, useEffect, useState } from 'react'; import { Sandpack, SandpackProps } from '@codesandbox/sandpack-react'; import '@codesandbox/sandpack-react/dist/index.css'; import { useTheme } from 'next-themes'; +import useInView from 'lib/hooks/useInView'; interface Props extends SandpackProps {} const RUASandpack: FC = ({ ...rest }) => { - const [mounted, setMounted] = useState(false); const { systemTheme, theme } = useTheme(); const currentTheme = theme === 'system' ? systemTheme : theme; - useEffect(() => setMounted(true), []); - - if (!mounted) return null; + const { ref, inView } = useInView(); return ( <> -
- +
+ {inView && ( + + )}
); diff --git a/components/mdx/Image.tsx b/components/mdx/Image.tsx index ce650f5..85d75fa 100644 --- a/components/mdx/Image.tsx +++ b/components/mdx/Image.tsx @@ -11,7 +11,7 @@ interface Props const Image = ({ src, alt }: Props) => { return ( <> -

+ { className={styles.image} /> {alt && {alt}} -

+ ); }; diff --git a/lib/hooks/useInView.ts b/lib/hooks/useInView.ts new file mode 100644 index 0000000..ad4ca33 --- /dev/null +++ b/lib/hooks/useInView.ts @@ -0,0 +1,25 @@ +import { useEffect, useRef, useState } from 'react'; + +const useInView = () => { + const ref = useRef(null); + const [inView, setInView] = useState(false); + + useEffect(() => { + const observer = new IntersectionObserver((entries, observer) => { + entries.forEach((entry) => { + if (entry.isIntersecting) { + if (ref.current) { + setInView(true); + observer.unobserve(ref.current); + } + } + }); + }); + + ref.current && observer.observe(ref.current); + }, []); + + return { ref, inView }; +}; + +export default useInView;