New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

@flagdeck/react

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@flagdeck/react

React components and hooks for Flagdeck feature flags

Source
npmnpm
Version
0.0.5
Version published
Weekly downloads
5
Maintainers
1
Weekly downloads
 
Created
Source

Flagdeck React SDK

npm version License: MIT

React components and hooks for integrating Flagdeck feature flags into your React applications.

Installation

npm install @flagdeck/react
# or
yarn add @flagdeck/react
# or
pnpm add @flagdeck/react

The React SDK internally depends on the Flagdeck JavaScript SDK, which is automatically installed as a dependency.

Quick Start

Wrap your app with the FlagdeckProvider and start using the hooks and components:

import { FlagdeckProvider, useFlag } from '@flagdeck/react';

function App() {
  return (
    <FlagdeckProvider 
      options={{ 
        apiKey: 'YOUR_API_KEY',
        realTimeUpdates: true,
      }}
      initialUserContext={{
        userId: 'user-123',
        attributes: {
          plan: 'premium'
        }
      }}
    >
      <YourApp />
    </FlagdeckProvider>
  );
}

function YourApp() {
  const { isEnabled, isLoading } = useFlag('my-feature-flag');
  
  if (isLoading) return <div>Loading...</div>;
  
  return (
    <div>
      {isEnabled ? 'Feature is enabled!' : 'Feature is disabled'}
    </div>
  );
}

Provider

FlagdeckProvider

The FlagdeckProvider component initializes the Flagdeck SDK and provides the client instance to all child components.

<FlagdeckProvider
  options={{
    apiKey: 'your-api-key',             // Required
    debug: true,                        // Optional: enables debug logging
    realTimeUpdates: true,              // Optional: enables real-time flag updates via SSE
    timeout: 5000,                      // Optional: API request timeout in ms
    enableCache: true,                  // Optional: enables caching of flag evaluations
    cacheTimeout: 30000,                // Optional: cache TTL in ms
    enableOfflineMode: true,            // Optional: enables offline fallback
    enableAnalytics: true,              // Optional: enables analytics tracking
  }}
  initialUserContext={{                 // Optional: initial user context
    userId: 'user-123',                 // User identifier
    attributes: {                       // User attributes for targeting
      country: 'US',
      plan: 'premium'
    }
  }}
  readyDelayMs={100}                    // Optional: delay before marking SDK as ready
>
  {children}
</FlagdeckProvider>

Hooks

useFlagdeck

Provides access to the Flagdeck client and context state:

const { 
  client,               // Flagdeck client instance
  isReady,              // True when SDK is initialized and ready
  error,                // Error object if SDK initialization failed
  userContext,          // Current user context
  setUserContext        // Function to update user context
} = useFlagdeck();

useFlag

Evaluates a boolean feature flag:

const { 
  isEnabled,            // Boolean flag value
  isLoading,            // True when flag is being evaluated
  error                 // Error object if evaluation failed
} = useFlag('feature-flag-key', false);

useFlagValue

Gets a feature flag value of any type:

const { 
  value,                // Flag value (can be any type)
  isLoading,            // True when flag is being evaluated
  error                 // Error object if evaluation failed
} = useFlagValue('theme-flag', 'default');

// Type-specific usage
const { value: count } = useFlagValue<number>('item-count', 10);

useFlags

Evaluates multiple flags at once:

const { 
  values,               // Record of flag keys to their values
  isLoading,            // True when flags are being evaluated
  errors                // Record of flag keys to error objects
} = useFlags(['flag-1', 'flag-2', 'flag-3'], false);

// Access individual flags
const isFeature1Enabled = values['flag-1'];

Components

FeatureFlag

Conditionally renders content based on flag state:

<FeatureFlag
  flagKey="new-dashboard"
  defaultEnabled={false}
  fallback={<OldDashboard />}
  loadingContent={<Loading />}
  onError={(error) => console.error(error)}
>
  <NewDashboard />
</FeatureFlag>

FlagValue

Render prop component for accessing flag values:

<FlagValue flagKey="color-theme" defaultValue="default">
  {({ value: theme, isLoading }) => (
    <div className={`theme-${theme}`}>
      Current theme: {isLoading ? 'Loading...' : theme}
    </div>
  )}
</FlagValue>

WithFeature

Render prop alternative for conditional rendering:

<WithFeature flagKey="premium-dashboard">
  {({ isEnabled, isLoading }) => (
    isLoading ? (
      <Loading />
    ) : isEnabled ? (
      <PremiumDashboard />
    ) : (
      <StandardDashboard />
    )
  )}
</WithFeature>

Real-time Flag Updates

The SDK supports real-time updates via Server-Sent Events (SSE). When enabled (via realTimeUpdates: true), flag changes made in the Flagdeck dashboard will be pushed to your application immediately without requiring page refreshes.

Targeting & User Context

Use the setUserContext function to update user targeting attributes:

const { setUserContext } = useFlagdeck();

// Switch user context
function switchUser(userId, plan) {
  setUserContext({
    userId,
    attributes: {
      plan,
      timestamp: Date.now()
    }
  });
}

Error Handling

All hooks provide error information that you can use to handle different error scenarios:

const { isEnabled, error } = useFlag('my-feature');

if (error) {
  if (error.type === 'notfound') {
    console.warn(`Flag "${error.flagKey}" not found`);
  } else if (error.type === 'inactive') {
    console.info(`Flag "${error.flagKey}" is currently inactive`);
  }
}

Advanced Examples

Using multiple providers for different parts of an application

// App.jsx
import { FlagdeckProvider } from '@flagdeck/react';

export default function App() {
  return (
    <FlagdeckProvider 
      options={{ apiKey: 'GLOBAL_API_KEY' }}
      initialUserContext={{ userId: 'current-user' }}
    >
      <MainApp />
      
      {/* Dashboard with separate Flagdeck context */}
      <FlagdeckProvider 
        options={{ apiKey: 'DASHBOARD_API_KEY' }}
        initialUserContext={{ userId: 'admin-user' }}
      >
        <AdminDashboard />
      </FlagdeckProvider>
    </FlagdeckProvider>
  );
}

Implementing a theme system with flags

function ThemeProvider({ children }) {
  const { value: theme } = useFlagValue('app-theme', 'light');
  
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
  }, [theme]);
  
  return <>{children}</>;
}

Feature gating entire routes

function ProtectedRoute({ flagKey, children, fallback = <Navigate to="/access-denied" /> }) {
  const { isEnabled, isLoading } = useFlag(flagKey);
  
  if (isLoading) return <Loading />;
  
  return isEnabled ? children : fallback;
}

// Usage
<Routes>
  <Route path="/" element={<Home />} />
  <Route 
    path="/premium" 
    element={
      <ProtectedRoute flagKey="premium-access">
        <PremiumContent />
      </ProtectedRoute>
    } 
  />
</Routes>

API Reference

For a complete API reference, see the Flagdeck Documentation.

License

MIT

Keywords

flagdeck

FAQs

Package last updated on 09 Apr 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts