The availability of features may depend on your plan type. Contact your Customer Success Manager if you have any questions.
Dev guideRecipesAPI ReferenceChangelog
Dev guideAPI ReferenceRecipesChangelogUser GuideGitHubDev CommunityOptimizely AcademySubmit a ticketLog In
Dev guide

Example usage of the React SDK v4+

Code example of how to use the Optimizely Feature Experimentation React SDK to send Decision events, make flag decisions and track conversion events.

Prerequisites

Before using the client to evaluate flag rules, including A/B tests and flag deliveries, you must complete the following:

  1. Install the React SDK.
  2. Initialize the React SDK.

Example React SDK implementation

This example walks through the following three key steps:

  1. Evaluate a flag with the key product_sort using the decide hooks. This also sends a decision event to Optimizely to record that the user was exposed to the experiment.

  2. Run code based on the flag result. The SDK evaluates your flag rules and determines which variation the user is in. You can either:

    • Check the flag's enabled state and read a configuration variable (sort_method) to determine which experience the user gets.
    • Check the flag variation directly and run the corresponding control or treatment code.
  3. Track a conversion event called purchased to measure the experiment's impact. The track event method ties the purchase back to the A/B test and sends it to Optimizely through the event dispatcher so it shows up on your results page.

import React from 'react';
import {
  createInstance,
  createPollingProjectConfigManager,
  createBatchEventProcessor,
  OptimizelyProvider,
  useDecide,
  useOptimizelyUserContext,
} from '@optimizely/react-sdk';

const optimizely = createInstance({
  projectConfigManager: createPollingProjectConfigManager({
    sdkKey: 'YOUR_SDK_KEY', // TODO: Update to your SDK Key
  }),
  eventProcessor: createBatchEventProcessor(),
});

function PurchaseButton() {
  const { userContext } = useOptimizelyUserContext();

  const handleClick = () => {
    userContext?.trackEvent('purchased');
  };

  return <button onClick={handleClick}>Purchase</button>;
}

function ProductSort() {
  const { decision, isLoading, error } = useDecide('product_sort');

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div className="error">{error.message}</div>;

  const variationKey = decision.variationKey;
  const isEnabled = decision.enabled;
  const sortMethod = decision.variables['sort_method'];

  return (
    <div>
      {/* If variation is null, display error */}
      {variationKey === null && <div className="error">{decision.reasons}</div>}

      {/* If feature is enabled, do something with the Sort Method variable */}
      {isEnabled && <div>The Sort method is {sortMethod}</div>}

      {/* Show relevant component based on the variation key */}
      {variationKey === 'control' && <div>Control Component</div>}
      {variationKey === 'treatment' && <div>Treatment Component</div>}

      {/* Show Purchase Button to track Purchase event */}
      <PurchaseButton />
    </div>
  );
}

function App() {
  return (
    <OptimizelyProvider client={optimizely} user={{ id: 'user123' }}>
      <ProductSort />
    </OptimizelyProvider>
  );
}

export default App;

Next

For a more step-by-step example, see the React SDK quickstart: