import { useContext, useCallback, useState } from 'react'; import { useOnMount } from './useOnMount'; import type { LoadableResult } from '../models'; import { HackleContext } from '../components'; import { InputUtil } from '../utils'; export function useLoadableFeature( featureKey: number ): LoadableResult { const { hackle, userVersion } = useContext(HackleContext); const getIsOn = useCallback(() => { return hackle?.isFeatureOn(featureKey) || Promise.resolve(false); }, [featureKey, hackle]); const [isOn, setIsOn] = useState(() => { if (!hackle) { return Promise.resolve(false); } return getIsOn(); }); const currentInput = { key: featureKey, userVersion, }; const [prevInput, setPrevInput] = useState(currentInput); if (!InputUtil.isInputEqual(prevInput, currentInput)) { setPrevInput(currentInput); setIsOn(getIsOn()); } return useOnMount(isOn, false); }