Introducing PrimeReact v11-alpha 🎉Discover Now

usePortal

Hook that tracks client-side mount state for SSR-safe portal rendering.

Portal Target

basic-demo

Usage#

import { usePortal } from '@primereact/headless/portal';
import { createPortal } from 'react-dom';
 
const portal = usePortal();
 
{
    portal.state.mounted && createPortal(<div></div>, document.body);
}

usePortal provides SSR-safe mount detection so portaled content is only rendered on the client — see Primitive for a component-based API.

Features#

  • state.mounted boolean for SSR-safe conditional rendering with React's createPortal
  • onMounted and onUnmounted lifecycle callbacks

Behavior#

Mount Detection#

Use state.mounted to guard createPortal calls. The hook returns false during SSR and becomes true after the component mounts on the client.

const portal = usePortal();
 
{
    portal.state.mounted && createPortal(<div>Portaled content</div>, document.body);
}

Lifecycle Callbacks#

Pass onMounted and onUnmounted to run side effects when the portal mounts or unmounts.

const portal = usePortal({
    onMounted: () => console.log('mounted'),
    onUnmounted: () => console.log('unmounted')
});

Custom Target#

Combine state.mounted with any DOM reference to portal content into a specific container.

const portal = usePortal();
const [container, setContainer] = React.useState<HTMLElement | null>(null);
 
<div ref={setContainer} />;
{
    portal.state.mounted && container && createPortal(<div>Content</div>, container);
}

API#

usePortal#

NameTypeDefault
onMounted() => void—
Callback function to invoke when the portal is mounted.
onUnmounted() => void—
Callback function to invoke when the portal is unmounted.

Accessibility#

See Portal Primitive for details.