Blog>
Snippets

Dynamic Feature Flagging with TanStack Config

Implement dynamic feature flagging to enable or disable application features in real-time based on environment-specific configurations managed by TanStack Config.
import { createConfig, getConfig } from 'tanstack-config';

// Initialize base configuration
createConfig({
  featureFlags: {
    newUI: false, // Default state
  },
});
This code snippet sets up the initial configuration using TanStack Config. A feature flag 'newUI' is defined with a default state of false, indicating the feature is disabled by default.
function updateFeatureFlags(newFlags) {
  const currentConfig = getConfig();
  // Merge new flags with existing configuration
  createConfig({
    ...currentConfig,
    featureFlags: {
      ...currentConfig.featureFlags,
      ...newFlags,
    },
  });
}
This function, 'updateFeatureFlags', allows dynamic updating of feature flags at runtime. It merges new flag values with the existing configuration, effectively enabling or disabling features on-the-fly.
function isFeatureEnabled(featureName) {
  const { featureFlags } = getConfig();
  return featureFlags[featureName];
}
This utility function 'isFeatureEnabled' checks if a specific feature is enabled by looking up the feature flag in the current configuration.
// Example usage
if (isFeatureEnabled('newUI')) {
  console.log('New UI feature is enabled');
  // Code to enable new UI
} else {
  console.log('New UI feature is disabled');
  // Code to fallback to old UI
}
This example demonstrates how to use the 'isFeatureEnabled' function to conditionally execute code based on the state of the 'newUI' feature flag.