@heights/react-use-google-optimize
v0.1.4
Published
React hook for Google Optimize experiments
Downloads
16
Readme
@heights/react-use-google-optimize
React hook for Google Optimize experiments.
Install
// Yarn
yarn add @heights/react-use-google-optimize
// NPM
npm i -S @heights/react-use-google-optimize
Usage
This hook uses the Optimize JavaScript API to retrieve the variant for a given experiment.
This hook is isomorphic, so it will always render the control until the client-side is ready and Optimize has loaded.
Example code:
import React from 'react'
import { useGoogleOptimize } from '@heights/react-use-google-optimize'
const App = () => {
const [isVariation] = useGoogleOptimize("OPTIMIZE_EXPERIMENT_ID")
return (
<>
<h1>{ isVariation ? "This is a variant" : "This is control" }</h1>
</>
)
}
You can also support multiple tests easily:
import React from 'react'
import { useGoogleOptimize } from '@heights/react-use-google-optimize'
const App = () => {
const [isExperimentOneVariation] = useGoogleOptimize("OPTIMIZE_EXPERIMENT_ID_ONE")
const [isExperimentTwoVariation] = useGoogleOptimize("OPTIMIZE_EXPERIMENT_ID_TWO")
return (
<>
<h1>{ isExperimentOneVariation ? "This is a variant for heading" : "This is a control heading" }</h1>
<p>{ isExperimentTwoVariation ? "This is a variant for description" : "This is a control description" }</p>
</>
)
}
Advanced Usage
It's possible to support a number of different variants in your test:
import React from 'react'
import { useGoogleOptimize } from '@heights/react-use-google-optimize'
enum VARIATIONS {
CONTROL,
VARIANT_A,
VARIANT_B
}
const variantText = (variant: number): string => {
switch(variant) {
case VARIATIONS.VARIANT_A: {
return ("This is Variant A")
}
case VARIATIONS.VARIANT_B: {
return ("THIS IS VARIANT B")
}
default: {
return ("THIS IS CONTROL")
}
}
}
const App = () => {
const [_, variation] = useGoogleOptimize("OPTIMIZE_EXPERIMENT_ID")
return (
<>
<h1>{variantText(variation)}</h1>
</>
)
}