Disclaimer: This website requires Please enable JavaScript in your browser settings for the best experience.

The availability of features may depend on your plan type. Contact your Customer Success Manager if you have any questions.

Dev guideRecipesAPI Reference
Dev guideAPI ReferenceUser GuideLegal TermsGitHubDev CommunityOptimizely AcademySubmit a ticketLog In
Dev guide

Initialize the React SDK

Initialize the Optimizely Feature Experimentation React SDK in your application.

Use the createInstance method to initialize the React SDK and instantiate an instance of the ReactSDKClient class. Each client corresponds to the datafile representing the state of a project for a certain environment.

Version

SDK v3.0.0 and higher

Description

The createInstance method accepts a configuration object to configure Optimizely Feature Experimentation.

Some parameters are optional because the React SDK provides a default implementation, but you may want to override these for your production environments. For example, you may want to override these to set up an error handler and logger to catch issues, an event dispatcher to manage network calls and a User Profile Service to ensure sticky bucketing.

Parameters

The table lists the required and optional parameters in React (created by passing in a Config object. The Config class consists of these fields).

ParameterTypeDescription
datafile
optional
stringThe JSON string representing the project. Either an SDK key or datafile (or both) must be provided.
sdkKey
optional
stringThe key associated with an environment in the project. At least one of sdkKey or datafile must be provided.
eventDispatcher
optional
objectAn event handler to manage network calls.
logger
optional
objectA logger implementation to log issues.
errorHandler
optional
objectAn error handler object to handle errors.
userProfileService
optional
objectA user profile service.
datafileOptions
optional
objectObject with configuration for automatic datafile management. Can have autoUpdate (boolean), urlTemplate (string) and updateInterval (number) properties.
defaultDecideOptions
optional
ArrayArray of OptimizelyDecideOption enums. When the Optimizely client is constructed with this parameter, it sets default decide options that are applied to all the Decide calls made during the lifetime of the Optimizely client. You can also pass options to individual Decide methods (does not override defaults). For details on decide options, see OptimizelyDecideOption.

Returns

Instantiates an instance of the Optimizely Feature Experimentation class.

Example

In the React SDK, you can provide either sdkKey or datafile or both.

  • When initializing with just the datafile, the SDK will use the given datafile.
  • When initializing with just the SDK key, the datafile will be automatically downloaded.
  • When initializing with both the SDK key and datafile, the SDK will use the given datafile to start, then download the latest version of the datafile in the background.

Instantiate using datafile

First, get a copy of the datafile from our server by including the following script in the of your web application. This script adds the datafile on the global window variable window.optimizelyDatafile

<script src="https://cdn.optimizely.com/datafiles/<Your_SDK_Key>.json/tag.js"></script>

Once you have a datafile, you can instantiate an Optimizely client.

import { createInstance } from '@optimizely/react-sdk';

const optimizely = createInstance({
  datafile: window.optimizelyDatafile,
})

Instantiate using SDK key

To instantiate using the SDK key, obtain the SDK key from your project's settings page, then pass sdkKey as a string property in the options object you pass to the createInstance method.

import { createInstance } from '@optimizely/react-sdk';

const optimizely = createInstance({
  sdkKey: '<Your_SDK_Key>',
});

When you provide the sdkKey, the SDK instance downloads the datafile associated with that sdkKey. When the download completes, the SDK instance updates itself to use the downloaded datafile. This initialize method relies on continuous Internet connectivity (in contrast, in the React Native SDK, you can initialize with an SDK Key even while your app is offline.)

Render an OptimizelyProvider with a client and user

To use React SDK components inside your app, render an OptimizelyProvider as the parent of your root app component. Provide your Optimizely instance as the optimizely prop and a user object:

import { OptimizelyProvider, createInstance  } from '@optimizely/react-sdk';

const optimizely = createInstance({
  datafile: window.datafile,
});

// using a function component
export default function App() {
 return (
   <OptimizelyProvider
     optimizely={optimizely}
     user={{id: '<Your_User_Id>'}}>
     <App />
   </OptimizelyProvider>
 );
}

// or a class component
class App extends React.Component {
  render() {
    return (
      <OptimizelyProvider
      	optimizely={optimizely}
  			user={{id: '<Your_User_Id>'}}>
        <App />
      </OptimizelyProvider>
    );
  }
}

Notes

Customize datafile management behavior

To customize datafile management behavior, provide a datafileOptions object property inside the options object passed to createInstance. The table lists the supported customizable options.

OptionTypeExplanation
autoUpdatebooleanWhen true, and sdkKey was provided in createInstance options, automatic updates are enabled on this instance. The default value is false.
updateIntervalnumberWhen automatic updates are enabled, this controls the update interval. The unit is milliseconds. The minimum allowed value is 1000 (1 second). The default value is 300000 milliseconds (5 minutes).
urlTemplatestringA format string used to build the URL from which the SDK will request datafiles. Instances of %s will be replaced with the sdkKey. When not provided, the SDK will request datafiles from the Optimizely CDN.

The following example shows how to customize datafile management behavior.

import { createInstance } from '@optimizely/react-sdk';

const optimizely = createInstance({
  sdkKey: '<Your_SDK_Key>',
  datafileOptions: {
    autoUpdate: true,
    updateInterval: 600_000, // 10 minutes in milliseconds
    urlTemplate: 'http://localhost:5000/datafiles/%s.json',
  },
});

Considerations when using development mode

If you have created your React application using Create React App or are using a different type of development environment that uses hot reloading, there is a possibility of experiencing unusual behavior.

When running your application in development mode with hot reloading, for example, when using npm start, you may see that the Optimizely Feature Experimentation SDK is initialized more than once. This may cause inconsistent behavior, such as the page re-rendering multiple times or users being bucketed into incorrect variations.

This is not a problem with the Optimizely Feature Experimentation React SDK. Instead, this happens when you wrap your application in React.StrictMode, which purposely renders the application twice in development mode to detect potential issues. To avoid this, disable the strict mode for the top-level component and move it to the lower-level components.

When building your app for production usenpm run build and hosting it on a web server, the Optimizely Feature Experimentation React SDK is not initialized more than once.

Dispose of the client

For effective resource management with the Optimizely React SDK, you must properly close the Optimizely client instance when it is no longer needed. This is done by calling optimizely.close().

The .close() method ensures that the processes and queues associated with the instance are properly released. This is essential for preventing memory leaks and ensuring that the application runs efficiently, especially in environments where resources are limited or in applications that create and dispose of many instances over their lifecycle.

See Close Optimizely Feature Experimentation React SDK on application exit.

OdpManager

OdpManager contains all the logic supporting Real-Time Segments for Feature Experimentation-related features, including audience segments.

The React SDK enables the Real-Time Segments for Feature Experimentation methods by default. But, the methods do nothing unless you have enabled and configured Real-Time Segments for Feature Experimentation.

If necessary, to disable Real-Time Segments for Feature Experimentation altogether, set disabled: true in the odpOptions. See the following sample code for information.

The following settings are optionally configurable when the React SDK is initialized:

  • ODP SegmentsCache size – segmentsCacheSize
    • Default – 100
    • Set to 0 to disable caching.
  • ODP SegmentsCache timeout (in seconds) – segmentsCacheTimeout
    • Default – 600 secs (10 minutes)
    • Set to 0 to disable timeout (never expires).
  • ODP enable – disabled
    • Default – false (enabled)
    • When disabled, the React SDK will disable ODP-related features. The React SDK still creates and manages VUID regardless of this flag and supports VUID-based decisions. See anonymous users.
    • The React SDK returns or logs an odpNotEnabled error when ODP is disabled and its features are requested.

OdpSegmentManager

This module provides an interface to the remote ODP server for audience segment mappings.

It fetches all qualified segments for the given user context and returns them as a string array in the completion handler.

It also manages a segment's cache shared for all user contexts. The cache is in memory (not persistent), and rebooting the device or terminating the app resets it.

OdpEventManager

This module provides an interface to the remote ODP server for events.

It queues all pending events (persistent) and sends them (in batches of up to 10) to the ODP server when all resources are available, including network connection and ODP public key (in the SDK's datafile).

📘

Notes

  • The React SDK tries to dispatch all events (stored in a persistent queue and retried on recoverable errors) but does not guarantee completion.
  • The React SDK does not have direct access to OdpManager, OdpSegmentManager, nor OdpEventManager. These are managed by the underlying Javascript SDK. There are configuration options that can be set during the Optimizely client instantiation.
// You must configure Real-Time Segments for Feature Experimentation

import { createInstance } from '@optimizely/react-sdk';

const optimizely = createInstance({
  sdkKey: '<Your_SDK_Key>',
  //...other Config options
  // The most common Real-Time Segments for Feature Experimentation control is to explicitly disable the feature 
  odpOptions: {
  	disabled: true,
  },
  // Other options are as defined by OdpOptions in the Javascript SDK
  // https://github.com/optimizely/javascript-sdk/blob/master/lib/shared_types.ts
});

Source files

The language and platform source files containing the implementation for React SDK are available on GitHub.