Blog>
Snippets

Managing Feature Flags with TanStack Config

Example code to manage and toggle feature flags in a React application using TanStack Config, enabling conditional rendering and feature rollout.
import { createConfig } from '@tanstack/config';

// Define your configurations and feature flags
export const appConfig = createConfig({
  key: 'myAppConfig',
  defaultConfig: {
    features: {
      newUI: false, // Feature flag for New UI
      betaFeature: false, // Feature flag for Beta Feature
    }
  }
});
This piece of code sets up the TanStack Config by defining the application configurations, including feature flags for 'newUI' and 'betaFeature'. These flags are initially set to false, indicating that the features are turned off by default.
import React, { useContext } from 'react';
import { ConfigContext } from './ConfigContext';
import { appConfig } from './appConfig';

// A React component that conditionally renders based on feature flags
const FeatureToggledComponent = () => {
  const config = useContext(ConfigContext);
  
  return (
    <div>
      {config.features.newUI && <div>New UI Enabled</div>}
      {config.features.betaFeature && <div>Beta Feature Enabled</div>}
    </div>
  );
};
This code snippet creates a React component that uses the 'useContext' hook to access the configuration context. It conditionally renders content based on the state of the 'newUI' and 'betaFeature' flags.
import React from 'react';
import { appConfig } from './appConfig';
import { ConfigProvider } from '@tanstack/config-react';
import FeatureToggledComponent from './FeatureToggledComponent';

// Wrap your application or component with ConfigProvider
function App() {
  return (
    <ConfigProvider config={appConfig}>
      <FeatureToggledComponent />
    </ConfigProvider>
  );
}

export default App;
This part shows how to use the 'ConfigProvider' from '@tanstack/config-react' to wrap the application or specific components within a provider. This ensures that any component within the provider's scope can access the application's configuration, including the feature flags.