Created
August 22, 2024 00:30
-
-
Save JLarky/db0826c365eb454206dd4ec8031f452c to your computer and use it in GitHub Desktop.
How to render component only on the server
This file contains 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
// https://x.com/JLarky/status/1826404005876301882 | |
export function FancyStuff(props: { getFromServer?: undefined | (() => string) }) { | |
const [mousePos, setMousePos] = useState('0, 0'); | |
useEffect(() => { | |
document.addEventListener('mousemove', (e) => { | |
setMousePos(`${e.clientX}, ${e.clientY}`); | |
}); | |
}, []); | |
return ( | |
<div> | |
Hello from client {mousePos} | |
<X>hello123 {props.getFromServer?.()}</X> | |
<X>hello123 {props.getFromServer?.()}</X> | |
</div> | |
); | |
} | |
export function X(props: { children: React.ReactNode }) { | |
const id = useId(); | |
const ssrOnly = useMemo(() => { | |
if (typeof window !== 'undefined') { | |
const el = document.querySelector(`[data-hid="${id}"]`); | |
if (el) { | |
console.log('hydrated from html', el); | |
return <div data-hid={id} dangerouslySetInnerHTML={{ __html: el.innerHTML }} />; | |
} | |
} | |
return; | |
}, [id]); | |
return ssrOnly || <div data-hid={id}>{props.children}</div>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment