DEV Community

Cover image for Build feature flags in React using the Context API: how to

Build feature flags in React using the Context API: how to

Riccardo Coppola on March 30, 2020

One of the tenets of lean development is "deliver fast, deliver often". Now, this can become tricky when you have to add new, big features to an a...
Collapse
 
franky47 profile image
François Best

Here's how I do it in TypeScript, using flags in the environment:

import React from 'react'

export interface FeatureProps {
  name: string
}

const Feature: React.FC<FeatureProps> = ({ name, children }) => {
  const enabled = useFeature(name)
  if (!enabled) {
    return null
  }
  return <>children</>
}

export default Feature

// --

export function useFeature(name: string) {
  const enabled = React.useMemo(() => {
    return process.env[`ENABLE_FEATURE_${name.toUpperCase()}`] === 'true'
  }, [name])
  return enabled
}

Usage:

<Feature name="foo">
  <Foo />
</Feature>

// .env
ENABLE_FEATURE_FOO=true
Collapse
 
ricca509 profile image
Riccardo Coppola • Edited

Nice one, I'm just not a fan of env vars for feature flags but if they work for you, they simplify the code!