@heights/react-use-google-optimize
TypeScript icon, indicating that this package has built-in type declarations

0.1.4 • Public • Published

@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>
    </>
  )
}

Package Sidebar

Install

npm i @heights/react-use-google-optimize

Weekly Downloads

5

Version

0.1.4

License

ISC

Unpacked Size

4.72 kB

Total Files

4

Last publish

Collaborators

  • heights-engineering
  • liammartens