useCMSContext Deep Dive
The useCMSContext hook provides access to the current CMS page data and context within an Archibald Storefront application.
Core Concepts
In Archibald, the CMS context is a central store for data related to the currently rendered page. This context is typically populated by the CMSProvider during the initial page load or route transition.
import { useCMSContext } from '@archibald/storefront';
function MyPageHeader() {
const { page } = useCMSContext();
if (!page) return null;
return (
<header>
<h1>{page.name}</h1>
<small>ID: {page.uid}</small>
</header>
);
}
Page Data Structure
The standard page object returned by the context follows the DefaultCMSPage interface:
| Property | Type | Description |
|---|---|---|
uid | string | The unique identifier of the page. |
uuid | string | The universal unique identifier of the page. |
name | string | The display name or title of the page. |
creationTime | string | (Optional) When the page was first created. |
modifiedTime | string | (Optional) When the page was last updated. |
Generic Type Support
If your application uses a customized CMS page model with additional properties, you can pass a generic type to useCMSContext to ensure full type safety.
interface CustomPage extends DefaultCMSPage {
metaDescription: string;
showHeroBanner: boolean;
}
const { page } = useCMSContext<DefaultCMSContextInterface & { page: CustomPage }>();
// Now page.metaDescription is correctly typed
console.log(page?.metaDescription);
How it Works Step-by-Step
- Request Initialization: When a user navigates to a CMS-driven route, Archibald's routing system identifies the need for CMS data.
- Data Fetching: The
CMSClientfetches the page structure and component data from the configured CMS provider (e.g., SAP Commerce, Contentful). - Context Population: The
CMSProvider(wrapping your application) receives this data and stores it in the__CMSContext. - Hook Execution: When
useCMSContext()is called within a component:- It uses the standard React
useContexthook to access the__CMSContext. - It performs an invariant check: If the hook is called outside of a
CMSProvider, it throws a descriptive error.
- It uses the standard React
- Returns Data: The hook returns the current context object, allowing your components to reactively update if the page data changes (e.g., during a live preview session).
Best Practice: Always guard your usage of the page property with a null check, as the context might be initialized with an empty state before the CMS data has finished loading.