How to use Google Optimize A/B test tool in a React SPA Application
Hello everyone.
Contents
How to install and use google optimize with React + Typescript in a SPA ?
I will teach you today how to use Google Optimize A/B test tool in a SPA (Single Page Application) architecture, for example while using NEXTJS like in my case.
First install the script by just adding
1 |
<script src="https://www.googleoptimize.com/optimize.js?id=YOURID" /> |
before including google analytics script.
By default google optimize is activated on page load and this is not what we want.
Change the activation event to “On custom event” and let it be “optimize.activate” (default one)
This means that we have to activate optimize manually. To do so, we are going to create a React hook in order to reuse it in all the components that rely on a particular experiment.
I am using Typescript, so the function at useOptimizeAB.ts
will look like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import { useEffect, useState } from 'react'; export default function useOptimizeAB(experimentId: string): number | undefined { const [variant, setVariant] = useState<number>(); useEffect(() => { window.dataLayer.push({ event: 'optimize.activate' }); const interval = setInterval(() => { if (window.google_optimize !== undefined) { const variant = window.google_optimize.get(experimentId); if (typeof variant !== 'undefined') { setVariant(Number(variant)); } clearInterval(interval); } }, 100); }, []); return variant; } |
How to use this ?
Just execute
1 |
const variant = useOptimizeAB('experiment id'); |
on the component you want to behave differently based on the A/B test.
Variant 0 is the original one, variant 1 is the remaining one (for one A/B test with only 2 variants 0 and 1). If you have more variants the number corresponds to the variant you created.
It is this simple, then you can use the variant
variable to change the page layout or logic whatever you want to do.
How to test locally?
Assuming you did all the steps above, the next good question will be how to test if this works locally ?
The answer is that it is very simple to do so by changing your host file.
If your domain is example.com, you can change your host file /etc/hosts (in linux systems) and add 127.0.0.1 example.com
Then every time you open example.com you will use localhost where your development site will be available. You can play around with the page you set as a target and console.log the variant and test the different results.
How to try out a new variant ?
At the time of this article you can change the last digit of the cookie named _gaexp
That is the variant id!
Simple as that, change the last digit for example from .0 to .1 and refresh the page. You will be using variant 1.
Or you can always hardcode the variant during development to see the different logics then for a integration test use the method above by modifying the cookie.