Skip to main content

useOptimisticVariant
component

The useOptimisticVariant takes an existing product variant, processes a pending navigation to another product variant, and returns the data of the destination variant. This makes switching product options immediate.

SelectedVariant
required

The selectedVariant field queried with variantBySelectedOptions.

Variants
required

The available product variants for the product. This can be an array of variants, a promise that resolves to an array of variants, or an object with a product key that contains the variants.

<SelectedVariant = >

A new product object where the selectedVariant property is set to the variant that matches the current URL search params. If no variant is found, the original product object is returned. The isOptimistic property is set to true if the selectedVariant has been optimistically changed.

Was this section helpful?

Example code

import {useLoaderData} from 'react-router';
import {useOptimisticVariant} from '@shopify/hydrogen';

export async function loader({context}) {
return {
product: await context.storefront.query('/** product query **/'),
// Note that variants does not need to be awaited to be used by `useOptimisticVariant`
variants: context.storefront.query('/** variants query **/'),
};
}

function Product() {
const {product, variants} = useLoaderData();

// The selectedVariant optimistically changes during page
// transitions with one of the preloaded product variants
const selectedVariant = useOptimisticVariant(
product.selectedVariant,
variants,
);

// @ts-ignore
return <ProductMain selectedVariant={selectedVariant} />;
}