Q48: How do you prevent a component from rendering during SSR in the Pages Router?
To render a component exclusively on the client in the Pages Router:
- Wrap import with
next/dynamic(() => import(...), { ssr: false }). - Or check
typeof window !== 'undefined'/ wrap render in auseEffectmounted state check.
Mounted Effect Pattern for Client-Only Rendering
import { useState, useEffect } from 'react';
export default function ClientOnly({ children }) {
const [hasMounted, setHasMounted] = useState(false);
useEffect(() => { setHasMounted(true); }, []);
if (!hasMounted) return null;
return <>{children}</>;
}💡 useEffect fires exclusively on the client after mount, preventing server pre-rendering of children.
Key Takeaways
- Use
next/dynamicwith{ ssr: false }. - Prevents hydration errors for window/document dependent libraries.
Knowledge Check
Why does evaluating window.innerWidth directly inside a component's render body cause a hydration mismatch error?