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

useOptimizelyUserContext for the React SDK v4+

Describes the useOptimizelyUserContext hook for the React SDK, which provides access to the current user context for event tracking and forced decisions.

Minimum SDK version

v4.0.0+

Description

The useOptimizelyUserContext hook returns the current OptimizelyUserContext object managed by the <OptimizelyProvider>. Use this hook for event tracking, forced decisions, and any operation that requires the user context.

To use this hook, call useOptimizelyUserContext within a component wrapped by OptimizelyProvider. See OptimizelyProvider for the React SDK.

Returns

Returns a UseOptimizelyUserContextResult object — a discriminated union with three possible states:

StateisLoadingerroruserContext
Loadingtruenullnull
ErrorfalseErrornull
SuccessfalsenullOptimizelyUserContext

Example — Event tracking

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

function PurchaseButton() {
  const { userContext, isLoading, error } = useOptimizelyUserContext();

  const handlePurchase = () => {
    if (userContext) {
      userContext.trackEvent('purchase', { revenue: 4200 });
    }
  };

  if (isLoading) return <Loading />;
  if (error) return <ErrorDisplay error={error} />;

  return <button onClick={handlePurchase}>Buy Now</button>;
}

Example — Forced decisions

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

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

  const forceVariation = () => {
    userContext?.setForcedDecision(
      { flagKey: 'flag-1', ruleKey: 'rule-1' },
      { variationKey: 'variation-a' }
    );
  };

  const clearForcedDecisions = () => {
    userContext?.removeAllForcedDecisions();
  };

  return (
    <div>
      <button onClick={forceVariation}>Force Variation A</button>
      <button onClick={clearForcedDecisions}>Clear All</button>
    </div>
  );
}

Source files

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