Use optimize-abtest in code
- Install
npm i optimize-abtest
oryarn add optimize-abtest
- Import
import useAbTest from 'optimize-abtest'
- Use
const { variant } = useAbTest('<yourAbTestName>');
to compare with stringvariant1
orvariant2
- Or simply use
const { isExperienceActive } = useAbTest('<yourAbTestName>');
if there's only 1 variant available
Set up Google Optimize experiment
- Create a new experiment
- Add a variant to it
- Edit Global JavaScript in the variant
- Add the next two lines of code listed below:
window.dispatchEvent(new CustomEvent('<yourAbTestName>', {detail: 'variant1'}));
document.cookie = "<yourAbTestName>=variant1";
A bit of explanation here
The package uses a session-long cookie named <yourAbTestName>
and one of its corresponding values either variant1
or variant2
. const { variant } = useAbTest('<yourAbTestName>');
returns one of the strings either variant1
or variant2
.
Alternatively, you can import a boolean isExperienceActive
witch return either variant1
is active or not.