Movatterモバイル変換


[0]ホーム

URL:


Dev guideRecipesAPI ReferenceChangelog
Dev guideAPI ReferenceRecipesChangelogUser GuideGitHubDev CommunityOptimizely AcademySubmit a ticketLog InFeature Experimentation
Dev guide
All
Pages
Start typing to search…

Initialize the React Native SDK

This topic describes how to initialize the Optimizely React Native SDK in your application.

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

Version

SDK v3.0.0 and higher

Description

ThecreateInstance 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 anerror handler andlogger to catch issues, an event dispatcher to manage network calls, and a User Profile Service to ensure sticky bucketing.

Parameters

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

Parameter

Type

Description

datafileoptional

string

The JSON string representing the project. At least one of sdkKey or datafile must be provided.

sdkKeyoptional

string

The key associated with an environment in the project. At least one of sdkKey or datafile must be provided.

eventDispatcheroptional

object

An event handler to manage network calls.

loggeroptional

object

A logger implementation to log issues.

errorHandleroptional

object

An error handler object to handle errors.

userProfileServiceoptional

object

A user profile service.

datafileOptionsoptional

object

Object with configuration for automatic datafile management. Can haveautoUpdate (boolean),urlTemplate (string), andupdateInterval (number) properties.

defaultDecideOptionsoptional

Array

Array ofOptimizelyDecideOption enums. When the Optimizely client is constructed with this parameter, it sets default decide options which are applied to all the Decide calls made during the lifetime of the Optimizely client. Additionally, you can pass options to individual Decide methods (does not overrides defaults). For details on decide options, seeOptimizelyDecideOption.

Returns

Instantiates an instance of theReactSDKClient class, a variation of the underlying JavaScript SDK Optimizely Client.

Example

In the React SDK, you can provide eithersdkKey ordatafile or both.

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

Instantiate using datafile

You can instantiate with a hard-coded datafile. If you do not pass in an SDK key, the React Native SDK Client does not automatically sync newer versions of the datafile. Any time you retrieve an updated datafile, just re-instantiate the same client. The hard-coded datafile can be a JSON or a valid JSON string.

To get the hard-coded datafile, copy the datafile JSON string fromthe app. Typically you would want to copy the datafile string at the latest point possible pre-release.

import { createInstance } from '@optimizely/react-sdk';const optimizely = createInstance({  datafile: optimizelyDatafile,})

Instantiate using SDK key

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

import { createInstance } from '@optimizely/react-sdk';const optimizely = createInstance({  sdkKey: '<Your_SDK_Key>',});

When you provide thesdkKey, the SDK instance downloads the datafile associated with thatsdkKey. When the download completes, the SDK instance updates itself to use the downloaded datafile.

Instantiate offline with SDK key

The React Native SDK provides default datafile caching to support fast initialization and offline mode. This means you can initialize using the SDK key even when there is no Internet connectivity. Once downloaded, the datafile is stored in the cache on the user's device. When the SDK is initialized the next time, it uses the datafile from the cache if available and resolves the ready promise. It then continues to load the latest datafile from the server. This results in faster SDK initialization.

Render anOptimizelyProvider with a client and user

To use React Native SDK components inside your app, render anOptimizelyProvider as the parent of your root app component. Provide your Optimizely Feature Experimentation instance as theoptimizely prop, and auser object:

import { OptimizelyProvider, createInstance  } from '@optimizely/react-sdk';const optimizely = createInstance({  datafile: window.datafile,});// using a function componentexport default function App() { return (   <OptimizelyProvider     optimizely={optimizely}     user={{id: '<Your_User_Id>'}}>     <App />   </OptimizelyProvider> );}// or a class componentclass 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 adatafileOptions object property inside theoptions object passed tocreateInstance. The table lists the supported customizable options.

OptionTypeExplanation
autoUpdatebooleanWhen true, andsdkKey was provided increateInstance options, automatic updates are enabled on this instance. The default value isfalse.
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 thesdkKey. 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',  },});

Dispose of the client

For effective resource management with the Optimizely React Native SDK, you must properly close the Optimizely client instance when it is no longer needed. This is done by callingoptimizely.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.

SeeClose Optimizely Feature Experimentation React Native SDK on application exit.

ODPManager

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

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

If necessary, to disable Real-Time Audiences for Feature Experimentation altogether, setdisabled: true in theodpOptions. See the following code sample for information.

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

  • ODP SegmentsCache sizesegmentsCacheSize
    • 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 enabledisabled
    • Default – false (enabled)
    • When disabled, the React Native SDK disables ODP-related features. The React Native SDK still creates and manages VUID regardless of this flag and supports VUID-based decisions. Seeanonymous users.
    • The React Native SDK returns or logs anodpNotEnabled 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 audience segments for the given user context and returns them as a string array in the completion handler.

It also manages an audience segments 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).

The React Native 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.

📘

Notes

  • The React Native SDK tries to dispatch all events (stored in a persistent queue and retried on recoverable errors) but does not guarantee completion.
  • The React Native SDK does not have direct access toOdpManager,OdpSegmentManager, norOdpEventManager. These are managed by the underlying Javascript SDK. There are configuration options that can be set during the Optimizely client instantiation.
// You must first configure Real-Time Audiences for Feature Experimentationimport { createInstance } from '@optimizely/react-sdk';const optimizely = createInstance({  sdkKey: 'YOUR_SDK_KEY',  //...other Config options  // The most common Real-Time Audiences 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 Native SDK are available onGitHub.

Updated 17 days ago



[8]ページ先頭

©2009-2025 Movatter.jp