← Back to React, page 8

react-0144 · Hard senior

How do you implement feature flags and A/B tests in a React application, and what pitfalls do you watch for?

Fetch flag values from a flag service (LaunchDarkly, Unleash, GrowthBook or your own) and expose them through a provider and a hook. Evaluate flags on the server where possible, so the first render has the right value and users do not see a flicker. Use stable user bucketing for experiments, log exposure when a user actually sees a variant, remove old flags quickly, and make sure each variant is tested and accessible.

Full answer

A feature flag is a runtime switch that decides which code path a user gets. An A/B test is a flag that assigns users to variants and measures a metric.

Architecture:

  • A flag source. A hosted service (LaunchDarkly, Statsig, GrowthBook, Unleash) or a simple JSON from your backend. It evaluates rules (percentage rollouts, user attributes, environments).
  • Delivery. For client-only apps, fetch flags at start and keep them in a context provider, with a useFlag('new-checkout') hook. For server rendering or Server Components, evaluate on the server and pass values to the client (as props or in a serialized payload), so the first HTML is already correct.
  • Usage. Keep conditionals small: choose between two components at one place rather than scattering checks. Provide safe defaults when the flag service is unreachable.

Experiment correctness:

  • Stable bucketing. Assign a user to a variant by hashing a stable id (user id or an anonymous cookie id) with the experiment key, so a user always sees the same variant across sessions and devices where possible.
  • Exposure events. Log an exposure when the variant is actually rendered to the user, not when the flag is evaluated, otherwise metrics are diluted.
  • Avoid flicker and layout shift. Do not render the control and swap to the variant after a request. Use server evaluation, edge middleware or a loading state.
  • Sample size and duration, and not stopping early, are statistical concerns that the team must respect.

Operational hygiene:

  • Short-lived flags have an owner and an expiry. Remove the flag and dead code once the rollout is complete.
  • Kill switches for risky features.
  • Test both branches in unit and end-to-end tests, and keep accessibility and performance equal across variants.
  • Do not use flags for security or authorization. The client can read and change anything it receives, so protect data on the server.
  • Be careful with bundle size: variants loaded with lazy avoid shipping unused code.

The example shows a flag provider, a hook and deterministic bucketing.

jsx
import { createContext, useContext } from 'react';

const FlagContext = createContext({});

function bucket(userId, experiment, variants) {
  let hash = 0;
  for (const char of userId + ':' + experiment) hash = (hash * 31 + char.charCodeAt(0)) >>> 0;
  return variants[hash % variants.length];
}

function useFlag(name, fallback = false) {
  const flags = useContext(FlagContext);
  return name in flags ? flags[name] : fallback;
}

function Checkout() {
  const variant = useFlag('checkout-experiment', 'control');
  console.log('exposure logged: checkout-experiment=' + variant);
  return <p>{variant === 'single-page' ? 'Single page checkout' : 'Classic checkout'}</p>;
}

export default function App() {
  const variant = bucket('user-42', 'checkout-experiment', ['control', 'single-page']);
  console.log('same user, same variant again: ' + (variant === bucket('user-42', 'checkout-experiment', ['control', 'single-page'])));
  return (
    <FlagContext value={{ 'checkout-experiment': variant }}>
      <Checkout />
    </FlagContext>
  );
}

The bucket function is deterministic, so the same user always gets the same variant. In a real system the flag service owns this rule, and the exposure line would be sent to analytics once per user and not on every render. Output of the run: same user, same variant again: true exposure logged: checkout-experiment=control

Key points

  • Flags come from a service and are exposed with a provider and a hook, with safe defaults.
  • Evaluate on the server where possible to avoid flicker and layout shift.
  • Bucket users with a stable hash, and log exposure when the variant is actually shown.
  • Remove flags and dead code after rollout, and test every variant.
  • Never use client flags as access control.

Common mistakes

  • Showing the control and swapping after the flags load, causing flicker.
  • Logging exposure when the flag is evaluated and not when it is seen.
  • Leaving finished flags and old branches in the code.
  • Using client-side flags to protect paid or private features.
  • Randomizing the variant on every visit.

Follow-ups

  • How would you serve flags with server rendering without flicker?
  • How do you test a component that depends on a flag?
  • What is a kill switch and how is it different from an experiment?

Tips

  • Separate flags from experiments, and name the extra rules of experiments.
  • Mention exposure logging and stable bucketing.
  • Close with flag cleanup.