import { useContext, useCallback, useState } from 'react'; import { HackleContext } from '../components'; import { DEFAULT_VARIATION } from '../models/Common'; import { InputUtil } from '../utils'; export function useVariation(experimentKey: number): string { const { hackle, userVersion } = useContext(HackleContext); const getVariation = useCallback(() => { return hackle?.variationSync(experimentKey) || DEFAULT_VARIATION; }, [experimentKey, hackle]); const [variation, setVariation] = useState(() => { if (!hackle) { return DEFAULT_VARIATION; } return getVariation(); }); const currentInput = { key: experimentKey, userVersion, }; const [prevInput, setPrevInput] = useState(currentInput); if (!InputUtil.isInputEqual(prevInput, currentInput)) { setPrevInput(currentInput); setVariation(getVariation()); } return variation; }