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.

Revisions

  1. sibelius created this gist May 6, 2020.
    37 changes: 37 additions & 0 deletions FeatureFlag.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    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;
    };
    22 changes: 22 additions & 0 deletions FeatureFlagUsage.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    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>
    )
    }