Render a cart from client side
Returning cart data, along with other data that builds a page, from a Remix loader server-renders the cart. However, if you want to turn on cache control for a page, then the cart shouldn't be server-rendered because carts are user-specific and should never be shared across different user sessions.
The cache control header structure is
public, max-age=1, stale-while-revalidate=9. There are many other cache-control configurations available, but this guide focuses on the
private: Only the client browser is allowed to cache the request. No servers are allowed to cache the content.
privatemode is helpful for user account pages, which are relatively static in nature but shouldn't have public servers caching the request due to personalized or sensitive content.
public: Public servers like Oxygen, or any other CDNs, are allowed to cache the request. The same content can be reused with multiple users requesting the same page. The content shouldn't contain personalized or sensitive content.
public cache control on your loader data, you'll need to convert your cart to render from the client side.
Benefits of turning on cache controlAnchor link to section titled "Benefits of turning on cache control"
- Static pages like blogs or articles can be cached longer
- You can expect cached pages to result in smaller response times compared to non-cached pages if they're served from Oxygen
Trade offs of turning on cache controlAnchor link to section titled "Trade offs of turning on cache control"
- Performance metric time to interactive (TTI) will be longer due to the delayed cart's request.
Step 1: Add a loader on your cart routeAnchor link to section titled "Step 1: Add a loader on your cart route"
Create a dedicated route to get a user's cart data. The route also serves as an API. You can get a user's cart by making a fetcher request to
Step 2: Create a provider and a hook for getting the cart dataAnchor link to section titled "Step 2: Create a provider and a hook for getting the cart data"
useCart hook to enable read access to a user's cart across the app:
Step 3: Include your Anchor link to section titled "Step 3: Include your CartProvider in your root"
CartProvider in your root
CartProvider component in your root layout so that your
useCart hook is available in the entire app.
Step 4: Get cart content with your Anchor link to section titled "Step 4: Get cart content with your useCart hook"
Access a user's cart data to do client-side UI rendering from anywhere in your app by using the
useCart hook within the
If you provide cart data in any Remix loaders, then make sure to remove them.