Skip to main content

usePreview Hook

Deprecation Notice

usePreview has been deprecated in favor of usePreviewNode

The usePreview hook provides an abstraction around getting a preview page or post from the Headless WordPress API. When calling the usePreview hook on an appropriate preview page, the hook will determine if the preview is a page or post and will make a request to retrieve the proper preview content.

The following example shows how to use the usePreview hook to render either a post or page from WordPress:

tip

This doc assumes you're storing your pages/styles/etc. in a directory called src, and you have the baseUrl option set to src in your tsconfig.json for importing modules from the root.

import { PageComponent } from 'pages/[...pageUri]';
import { PostComponent } from 'pages/posts/[postSlug]';
import { client } from 'client';

export default function Preview() {
const { usePreview } = client.auth;
const result = usePreview();

if (client.useIsLoading() || !result) {
return <p>loading...</p>;
}

if (result.type === 'page') {
if (!result.page) {
return <>Not Found</>;
}

return <PageComponent page={result.page} />;
}

if (!result.post) {
return <>Not Found</>;
}

return <PostComponent post={result.post} />;
}