DEV Community

loading...

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

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 Author

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