Last active
April 20, 2025 22:10
-
-
Save cmorten/606f223bfa555339b5b4ccf865678263 to your computer and use it in GitHub Desktop.
React Hydrate On View
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useEffect, useRef, useState } from 'react'; | |
| export function HydrateOnView({ children }: { children: React.ReactNode }) { | |
| const ref = useRef<HTMLElement>(null); | |
| const [inView, setInView] = useState(false); | |
| useEffect(() => { | |
| if (!ref.current || inView) return; | |
| const observer = new IntersectionObserver(([entry]) => { | |
| if (entry.isIntersecting) { | |
| observer.disconnect(); | |
| startTransition(() => { | |
| setInView(true); | |
| }); | |
| } | |
| }); | |
| observer.observe(ref.current); | |
| return () => observer.disconnect(); | |
| }, [hydrated]); | |
| // On the server, always render children | |
| if (typeof window === 'undefined') { | |
| return <div>{children}</div>; | |
| } | |
| return ( | |
| <div | |
| ref={ref} | |
| suppressHydrationWarning | |
| dangerouslySetInnerHTML={!inView ? { __html: '' } : undefined} | |
| > | |
| {inView ? children : null} | |
| </div> | |
| ); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useEffect, useRef, useState, Suspense } from "react"; | |
| export function HydrateOnView({ children }: { children: React.ReactNode }) { | |
| const ref = useRef<HTMLElement>(null); | |
| const [inView, setInView] = useState(false); | |
| useEffect(() => { | |
| if (!ref.current || inView) return; | |
| const observer = new IntersectionObserver(([entry]) => { | |
| if (entry.isIntersecting) { | |
| observer.disconnect(); | |
| startTransition(() => { | |
| setInView(true); | |
| }); | |
| } | |
| }); | |
| observer.observe(ref.current); | |
| return () => observer.disconnect(); | |
| }, [inView]); | |
| return ( | |
| <div ref={ref}> | |
| <Suspense fallback={null}> | |
| <MaybeSuspend suspend={!inView}>{children}</MaybeSuspend> | |
| </Suspense> | |
| </div> | |
| ); | |
| } | |
| function MaybeSuspend({ | |
| suspend, | |
| children, | |
| }: { | |
| suspend: boolean; | |
| children: React.ReactNode; | |
| }) { | |
| if (suspend) { | |
| throw new Promise(() => {}); | |
| } | |
| return <>{children}</>; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment