Created
October 4, 2021 16:24
-
-
Save KASOGIT/18fa5aebdf4b9d51f6a25ae9982eb08f to your computer and use it in GitHub Desktop.
useFeature flag hook
This file contains hidden or 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
declare global { | |
interface Window { | |
flags: { | |
enableFlag?: (name: string) => void; | |
disableFlag?: (name: string) => void; | |
}; | |
} | |
} | |
const FeatureFlagsContext = React.createContext({}); // flag names | |
export function useFeatureFlags() { | |
const [flags, setFlags] = React.useState({}); | |
const enableFlag = React.useCallback( | |
(flagName: string) => { | |
setFlags((prevFlags) => ({ ...prevFlags, [flagName]: true })); | |
}, | |
[setFlags] | |
); | |
const disableFlag = React.useCallback( | |
(flagName: string) => { | |
setFlags((prevFlags) => ({ ...prevFlags, [flagName]: false })); | |
}, | |
[setFlags] | |
); | |
React.useEffect(() => { | |
window.flags = { | |
enableFlag, | |
disableFlag, | |
}; | |
}, [disableFlag, enableFlag]); | |
return flags; | |
} | |
export function useIsFeatureFlag(flagName: string) { | |
const flags = React.useContext(FeatureFlagsContext); | |
return flags[flagName]; | |
} | |
// usage | |
function App() { | |
const flags = useFeatureFlags(); | |
return ( | |
<FeatureFlagsContext.Provider value={flags}> | |
<div> | |
<h1>Feature Flags</h1> | |
</div> | |
</FeatureFlagsContext.Provider> | |
); | |
} | |
function Component() { | |
const isFlagEnabled = useIsFeatureFlag("flag-name"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment