1.1.1 • Published 2 years ago

@andrewizbatista/use-feature-flags v1.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

useFeatureFlags

A simple React hook that encapsulates the logic around feature flags with ZERO dependencies.

Created by♥ @andrewizbatista

Table of Contents

Getting Started

Prerequisites

This package has peerDependencies that are required for you to include in your app's dependencies:

{
  "dependencies": {
    "react": "^17.0.2"
  }
}

Installing

yarn

yarn add @andrewizbatista/use-feature-flags

npm

npm install @andrewizbatista/use-feature-flags

Usage

1. Setup your Feature Flags

Create a file to initialize your feature flags (eg: src/feature-flags.ts) export the useFeatureFlags hook that is generated by the createFeatureFlags.

Don't forget to properly define Envs and FeatureFlags types to take full advantage of TypeScript.

// src/feature-flags.ts

import { createFeatureFlags } from '@andrewizbatista/use-feature-flags';

/**
 * List of environments your app supports
 */
type Envs = 'development' | 'stagging' | 'production';

/**
 * List of feature flags your app supports
 */
type FeatureFlags = 'FLAG_1' | 'FLAG_2' | 'FLAG_3';

/**
 * Environment variable
 */
const ENV = process.env.NODE_ENV;

/**
 * Create and export the `useFeatureFlags` hook
 */
export const { useFeatureFlags } = createFeatureFlags<Envs, FeatureFlags>(ENV, {
  /**
   * Enabled on every environment
   */
  FLAG_1: true,
  /**
   * Disabled on every environment
   */
  FLAG_2: false,
  /**
   * Enable/Disable per environment
   */
  FLAG_3: {
    development: true,
    stagging: true,
    production: false,
  },
});

2. Use the useFeatureFlags hook

You can access your feature flags using the useFeatureFlags hook anywhere on your app.

import { useFeatureFlags } from 'src/feature-flags';

function Page({ children }) {
  const { NAVIGATION_V2 } = useFeatureFlags();

  return (
    <Layout>
      {NAVIGATION_V2 ? <NavigationV2 /> : <Navigation />}
      <Content>{children}</Content>
      <Footer />
    </Layout>
  );
}

Contributing

Want to help? Feel free to open an Issue or create a Pull Request and let's get started 🚀

License

MIT © André Batista (@andrewizbatista) 🎉