Created
May 6, 2020 12:33
-
-
Save sibelius/f281f16a184a632a68bbb24ba15ded3c to your computer and use it in GitHub Desktop.
Basic Feature Flag implementation using React.Context
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 React, { useContext, useCallback } from 'react'; | |
export const FeatureFlagContext = React.createContext<string[]>([]); | |
export const useFeatureFlag = () => { | |
const features = useContext<string[]>(FeatureFlagContext); | |
const hasFeature = useCallback( | |
(feature: string) => { | |
return features.includes(feature); | |
}, | |
[features] | |
); | |
return { | |
hasFeature | |
}; | |
}; | |
type Props = { | |
feature: string; | |
children: React.ReactNode; | |
fallbackComponent?: React.ReactNode; | |
}; | |
export const FeatureFlag = ({ | |
feature, | |
fallbackComponent = null, | |
children | |
}: Props) => { | |
const { hasFeature } = useFeatureFlag(); | |
if (!hasFeature(feature)) { | |
return fallbackComponent; | |
} | |
return children; | |
}; |
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
export const AppFeatureFlags = { | |
TEMP: 'TEMP' // special feature flag that should wrap all WIP code | |
// TODO - add more features as you need | |
}; | |
export const getFeatureFlags = () => { | |
if (process.env.NODE_ENV === 'development') { | |
return [AppFeatureFlags.TEMP]; | |
} | |
return []; | |
}; | |
const Providers = ({ children }) => { | |
const features = useMemo(() => getFeatureFlags(), []); | |
return ( | |
<FeatureFlagContext.Provider value={features}> | |
{children} | |
</FeatureFlagContext.Provider> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment