The useSelectedVariant hook is a React hook designed to manage the selection of a product variant.


The useSelectedVariant hook provides methods and values to manage the selection of a product variant.

import { useSelectedVariant } from "builderoo";
const { variant, onSelectOption, isOptionSelected, preferredMedia, setPreferredMedia } = useSelectedVariant(product)


productProductThe product object for which the variant selection will be managed.
initialSelectedVariant0(optional) The pre-selected variant, if needed.

Return Values

variantobjectThe currently selected product variant.
onSelectOptionfunctionA function to toggle (set or unset) an option selection.
isOptionSelectedfunctionA function to check if a specific variant option is currently selected.
preferredMediaMediaThe optimal media items from based on user selected options (via onSelectOption().
setPreferredMediafunctionSet preferredMedia manually. This state setter can be used to change the value when user manually selects another media. preferredMedia resets when onSelectOption() is called.


Here’s an example of how to use the useSelectedVariant hook to manage product variant selection:

import React from 'react';
import { useSelectedVariant } from 'builderoo';
import classNames from "classnames";
function ProductDetail({ product }) {
  const { variant, onSelectOption, isOptionSelected } = useSelectedVariant(product);
  return (
    <div className="product-detail">
      <p>Price: ${variant.price}</p>
      <ul className="space-y-3 mt-4">
        { product.options && product.options.length > 0 &&, i) => (
          <li key={i} className="w-20">
            <div className="text-sm">{}</div>
            <ul className="flex gap-3 mt-1">
              {, i) => (
                  onClick={() => onSelectOption(option._id, value._id)}
                    "border border-gray-300 rounded-sm px-3 py-1 text-sm cursor-pointer",
                    {"bg-black text-white": isOptionSelected(value._id)},
                    {"bg-muted-background text-black": !isOptionSelected(value._id)},
export default ProductDetail;

In this example, the ProductDetail component uses the useSelectedVariant hook to manage the selection of a product variant. It displays the product’s name, price, and a list of variant options as buttons. The onSelectOption function allows users to select a variant, and isOptionSelected checks if an option is currently selected.