Set up React Web SDK

Install the package

$yarn add @launchdarkly/react-sdk

Initialize the SDK for feature management

React Web SDK initialization
1// Add the code below to the root of your React app.
2import { createRoot } from 'react-dom/client';
3import { createLDReactProvider, LDContext } from '@launchdarkly/react-sdk';
4
5function App() {
6 return <div>Let your feature flags fly!</div>
7}
8
9// A "context" is a data object representing users, devices, organizations, and other entities.
10const context: LDContext = {
11 kind: 'user',
12 key: 'EXAMPLE_CONTEXT_KEY',
13 email: '[email protected]',
14};
15
16// This is your client-side ID.
17const LDReactProvider = createLDReactProvider('YOUR_CLIENT_SIDE_ID', context);
18
19createRoot(document.getElementById('root') as HTMLElement).render(
20 <LDReactProvider>
21 <App />
22 </LDReactProvider>,
23);

Initialize the SDK for feature management and Experimentation

If you want to use the LaunchDarkly Experimentation feature, include a track call in your initialization code:

React Web SDK initialization for Experimentation
1// Add the code below to the root of your React app.
2import { StrictMode, useCallback } from 'react';
3import { createRoot } from 'react-dom/client';
4import { createLDReactProvider, useLDClient } from '@launchdarkly/react-sdk';
5
6function App() {
7 const ldClient = useLDClient();
8 // Call trackMetric when a metric action occurs in your app —
9 // a click, a form submit, a page view, a custom event, whatever your metric measures.
10 const trackMetric = useCallback(
11 (metricKey: string, data?: unknown) => {
12 ldClient?.track(metricKey, data);
13 },
14 [ldClient],
15 );
16 return <div>Let your feature flags fly!</div>;
17}
18
19// A "context" is a data object representing users, devices, organizations, and other entities.
20const context = {
21 kind: 'user',
22 key: 'EXAMPLE_CONTEXT_KEY',
23 email: '[email protected]',
24};
25
26// Initialize the SDK so flag values are ready before your app renders.
27// This is your client-side ID.
28const LDProvider = createLDReactProvider('YOUR_CLIENT_SIDE_ID', context);
29
30createRoot(document.getElementById('root') as HTMLElement).render(
31 <StrictMode>
32 <LDProvider>
33 <App />
34 </LDProvider>
35 </StrictMode>,
36);

You can find your server-side SDK keys, mobile keys, and client-side ID on the SDK keys page under Settings.

To learn more, read Initialize the client in the React Web SDK reference guide.