CMSClientProvider
This is a React component that makes the CMSClient instance available to all descendant components via React's context. It is the necessary wrapper for all CMS-related hooks (usePage, useCMSClient, etc.) to function correctly.
Usage
You should wrap a high-level component, typically your main App component, with the CMSClientProvider. It requires an instance of CMSClient to be passed as a prop.
This diagram illustrates how the CMSClient is instantiated and then provided to the application:
The corresponding code looks like this:
// 1. Create the client instance in its own file
// shop/client/api/creators/cms.ts
import { CMSClient } from '@archibald/cms';
const cmsClient = new CMSClient({
adapter: CommerceCMSAdapter,
api
});
export default cmsClient;
// 2. Import and use the provider in your main App component
// shop/client/components/App.tsx
import { CMSClientProvider } from '@archibald/cms';
import cmsClient from 'shop/client/api/creators/cms';
function App() {
return (
<CMSClientProvider client={cmsClient}>
<AppLayout>
<AppRoutes />
</AppLayout>
</CMSClientProvider>
);
}
For cleaner provider nesting, consider using the ProviderComposer as shown in the Connecting a Custom CMS guide.
Props
| Name | Type | Description |
|---|---|---|
client | CMSClient | An instance of the CMSClient. |
children | ReactNode | The React components to be rendered within the provider. |
Deep Dive
Description: The CMSClientProvider is more than just a simple context provider. It also performs a crucial one-time initialization of the CMSClient instance, connecting it with other framework clients like DataClient and AppClient. It also handles creating a new instance of the client during Server-Side Rendering (SSR) to avoid shared state between requests.
-
How To: The provider's usage is straightforward: wrap your application and pass the client instance. The internal logic handles the rest. Its presence is what allows hooks like
useCMSClientto retrieve the client instance from anywhere in the component tree. -
Best Practice: There should only be one
CMSClientProviderin your application's component tree. Placing it at the highest level ensures that the sameCMSClientinstance is available everywhere. Avoid wrapping smaller, individual components with their own provider, as this would lead to incorrect behavior and break the singleton pattern of the client.