DEV Community

Cover image for πŸ” Implementing Feature Flags in React via Permix
Valerii Strilets
Valerii Strilets

Posted on β€’ Edited on

1 1

πŸ” Implementing Feature Flags in React via Permix

Feature flags are a powerful technique that allows developers to modify system behavior without changing code. They're particularly useful for A/B testing, gradual rollouts, or managing beta features. Today, I'll show you how to implement feature flags in a React application using Permix.

What is Permix?

Permix is a lightweight, type-safe library for managing permissions and feature flags in TypeScript applications. It provides a simple API and React hooks/components for checking permissions.

Installation

Use your favorite package manager to install Permix:

npm install permix
Enter fullscreen mode Exit fullscreen mode

Implementation

Let's implement feature flags for a simple app with beta features.

1. Define Feature Flags

First, create a file to define your Permix instance with feature flags:

// lib/permix.ts
import { createPermix } from 'permix'
import { createComponents } from 'permix/react'

// Define permix instance with feature flags
export const permix = createPermix<{
  darkMode: {
    action: 'enabled'
  }
  betaFeatures: {
    action: 'newUI' | 'experimentalAPI'
  }
}>()

// Not necessary, but you can use components to check permissions
export const { Check } = createComponents(permix)

// Define feature flags
export const betaUserFeatures = permix.template({
  darkMode: {
    enabled: true,
  },
  betaFeatures: {
    newUI: true,
    experimentalAPI: true,
  },
})

export const regularUserFeatures = permix.template({
  darkMode: {
    enabled: true,
  },
  betaFeatures: {
    newUI: false,
    experimentalAPI: false,
  },
})
Enter fullscreen mode Exit fullscreen mode

2. Setup Feature Flags

export async function setupFeatureFlags() {
  const user = await getUser()

  const featureConfig = user.isBetaUser
    ? betaUserFeatures()
    : regularUserFeatures()

  permix.setup(featureConfig)
}
Enter fullscreen mode Exit fullscreen mode

3. Create a Custom Hook

For convenience, create a custom hook to use Permix:

import { usePermix } from 'permix/react'
import { permix } from '../lib/permix'

export function usePermissions() {
  return usePermix(permix)
}
Enter fullscreen mode Exit fullscreen mode

4. Using Feature Flags

Here's how to use feature flags in your React components:

import { useEffect } from 'react'
import { usePermissions } from './hooks/use-permissions'
import { permix, Check, setupFeatureFlags } from './lib/permix'

export default function App() {
  const { check } = usePermissions()

  useEffect(() => {
    setupFeatureFlags()
  }, [])

  // Conditionally render based on feature flag
  if (!check('betaFeatures', 'newUI')) {
    return null
  }

  async function handleApiCall() {
    // Check feature flag before executing code
    if (!permix.check('betaFeatures', 'experimentalAPI')) {
      return
    }

    console.log('Calling experimental API...')
  }

  return (
    <div>
      <h1>New UI</h1>
      <Check entity="betaFeatures" action="experimentalAPI">
        <button type="button" onClick={handleApiCall}>
          Call experimental API
        </button>
      </Check>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Benefits of Using Permix

  • 100% type-safe without writing TypeScript (except for initialization)
  • Single source of truth for your entire app
  • Perfect match for TypeScript monorepos
  • Zero dependencies
  • Useful methods for specific cases
  • Large number of integrations for different frameworks, such as React, Vue, Next.js, and more.

Summary

Permix provides a robust solution for implementing feature flags in React applications. Its type-safe approach and simple API make it an excellent choice for managing feature rollouts and user permissions.

The complete example code is available on GitHub, and you can find more information in the Permix documentation.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (2)

Collapse
 
dzungnt98 profile image
Dzung Nguyen β€’ β€’ Edited

Nice post! I'm really looking forward to your another post on this topic and library that do the same thing

Collapse
 
letstri profile image
Valerii Strilets β€’

Thans, I will definitely write more articles about Permix!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay