useIsMounted
Check if component is mounted for safe client-side operations.
useIsMounted
The useIsMounted hook returns whether the component has mounted on the client. This is useful for avoiding hydration mismatches with client-only features.
Usage
import { useIsMounted } from '@/hooks';
function ClientOnlyComponent() {
const isMounted = useIsMounted();
// Don't render client-only content during SSR
if (!isMounted) {
return <Skeleton />;
}
return (
<div>
Window width: {window.innerWidth}px
</div>
);
}
API
function useIsMounted(): boolean
Returns
boolean - false during SSR and initial render, true after mount.
When to Use
- Browser APIs - Access window, document, localStorage
- Avoid hydration mismatch - When server and client render differently
- Client-only libraries - Initialize libraries that don't support SSR
Example: localStorage
function UserPreferences() {
const isMounted = useIsMounted();
const [theme, setTheme] = useState('light');
useEffect(() => {
if (isMounted) {
const saved = localStorage.getItem('theme');
if (saved) setTheme(saved);
}
}, [isMounted]);
// Show default until mounted to prevent hydration mismatch
return <div data-theme={isMounted ? theme : 'light'}>...</div>;
}