Skip to content

Instantly share code, notes, and snippets.

@mrkaluzny
Created February 17, 2023 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrkaluzny/32405ce0a785da9cb8f5bfac5530835a to your computer and use it in GitHub Desktop.
Save mrkaluzny/32405ce0a785da9cb8f5bfac5530835a to your computer and use it in GitHub Desktop.
React/Next.js Google Optimize A/B Test implementation Hook
import { useEffect, useState } from "react";
const useExperiment = (
experimentId,
defaultVariant,
event = "optimize.activate"
) => {
const [variant, setVariant] = useState(defaultVariant);
useEffect(() => {
if (window.dataLayer) {
window.dataLayer.push({ event: event });
}
const intervalId = setIntervalWithLimit(() => {
if (window.google_optimize !== undefined) {
const variantLoaded = window.google_optimize.get(experimentId);
setVariant(Number(variantLoaded) || 0);
clearInterval(intervalId);
}
}, 200);
return () => clearInterval(intervalId);
}, []);
return { variant };
};
export default useExperiment;
// Function that creates interval and resets it if the code runs more than 20 times
function setIntervalWithLimit(callback, delay, limit = 20) {
let counter = 0;
const interval = setInterval(() => {
if (counter >= limit) {
clearInterval(interval);
}
callback();
counter++;
}, delay);
return interval;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment