Skip to main content

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:

PropertyTypeDescription
uidstringThe unique identifier of the page.
uuidstringThe universal unique identifier of the page.
namestringThe display name or title of the page.
creationTimestring(Optional) When the page was first created.
modifiedTimestring(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

  1. Request Initialization: When a user navigates to a CMS-driven route, Archibald's routing system identifies the need for CMS data.
  2. Data Fetching: The CMSClient fetches the page structure and component data from the configured CMS provider (e.g., SAP Commerce, Contentful).
  3. Context Population: The CMSProvider (wrapping your application) receives this data and stores it in the __CMSContext.
  4. Hook Execution: When useCMSContext() is called within a component:
    • It uses the standard React useContext hook to access the __CMSContext.
    • It performs an invariant check: If the hook is called outside of a CMSProvider, it throws a descriptive error.
  5. 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.