Created
February 17, 2023 15:38
-
-
Save mrkaluzny/32405ce0a785da9cb8f5bfac5530835a to your computer and use it in GitHub Desktop.
React/Next.js Google Optimize A/B Test implementation Hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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