npm i @react-hook/google-optimize
A React hook for using Google Optimize variants in components
Using the useGoogleOptimize
hook requires that you've installed Google Tag Manager
and created Google Optimize test cases.
import useGoogleOptimize from '@react-hook/google-optimize'
// Test React components
const CartABTest = (props) => {
const CartVariant = useGoogleOptimize('experimentId', [CartA, CartB, CartC])
return !CartVariant ? 'Loading...' : <CartVariant {...props} />
}
// Test any value
const CartABValueTest = (props) => {
const variant = useGoogleOptimize('experimentId', [false, true])
return variant === null ? (
'Loading...'
) : variant ? (
<CartA {...props} />
) : (
<CartB {...props} />
)
}
function useGoogleOptimize<T>(
experimentId: string,
variants: T[],
timeout?: number
): T | null
Argument | Type | Default | Required? | Description |
---|---|---|---|---|
experimentId | string |
undefined |
Yes | Your Google Optimize experiment id |
variants | T[] |
undefined |
Yes | Two or more experiment variants. The first variant is considered the default. |
timeout | number |
Infinity |
No | This hook will timeout and select the first variant by default if Google Optimize doesn't load within timeout milliseconds. By default, this hook will never timeout. |
This hook returns the variant selected by Google Optimize. While the variant selection is loading,
this hook returns null
.
In the future this hook snould cause the component to suspend until the variant is available.
MIT