Skip to content

Instantly share code, notes, and snippets.

@sibelius
Created May 6, 2020 12:33
Show Gist options
  • Save sibelius/f281f16a184a632a68bbb24ba15ded3c to your computer and use it in GitHub Desktop.
Save sibelius/f281f16a184a632a68bbb24ba15ded3c to your computer and use it in GitHub Desktop.
Basic Feature Flag implementation using React.Context
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;
};
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