LaunchDarkly React Client SDK

3.9.0 · active · verified Sun Apr 19

The `launchdarkly-react-client-sdk` is the official client-side SDK for integrating LaunchDarkly feature flags into React applications. It leverages React's Context API and Hooks to provide a convenient way to access flag values and the LaunchDarkly client instance throughout a component tree. The current stable version is 3.9.0. This SDK typically sees several releases per year, often driven by updates to the underlying `js-client-sdk` and new React features. Key differentiators include its tight integration with React's component lifecycle, providing hooks like `useFlags` and `useLDClient`, and simplifying prop drilling for feature flags. It's designed for modern React development, compatible with React 16.3.0+, with Hooks requiring 16.8.0+.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes the LaunchDarkly SDK using `withLDProvider`, setting up an anonymous user and then demonstrating how to retrieve flag values within a functional component using the `useFlags` hook. It includes basic error handling for a missing client-side ID.

import React from 'react';
import { withLDProvider, useFlags } from 'launchdarkly-react-client-sdk';

const clientSideId = process.env.REACT_APP_LD_CLIENT_SIDE_ID ?? '';

if (!clientSideId) {
  console.error('LaunchDarkly Client-side ID is not set. Please set REACT_APP_LD_CLIENT_SIDE_ID in your environment variables.');
}

interface MyComponentProps {
  // any props for your component
}

const MyFeatureComponent: React.FC<MyComponentProps> = () => {
  const { myFeatureFlag, anotherFlag } = useFlags();

  return (
    <div>
      <h1>My Application</h1>
      {myFeatureFlag ? (
        <p>Feature is ON! Displaying content for the feature.</p>
      ) : (
        <p>Feature is OFF. Default content.</p>
      )}
      {anotherFlag && <p>Another flag is also ON!</p>}
    </div>
  );
};

const MyWrappedComponent = withLDProvider({
  clientSideId: clientSideId,
  user: { key: 'example-user', anonymous: true },
  options: { 
    evaluationReasons: true 
  }
})(MyFeatureComponent);

export default MyWrappedComponent;

view raw JSON →