"The perils of rehydration"

In React apps that use SSR, where your component code can run both on the server and on the client, it's sometimes important to know where your code is currently running.

In "The Perils of Rehydration", Josh Comeau talks about why the following is a problem for rehydration:

const Component = () => { if (typeof window === 'undefined') { return null } // Client-only code return <>...</>; }

And why waiting until after the Component mounts can help avoid rehydration issues:

const Component = () => { const [hasMounted, setHasMounted] = useState(false); useEffect(() => { setHasMounted(true); }, []); if (!hasMounted) { return null; } // Client-only code return <>...</>; }

August 3, 2021 at 2:50 AM