useOptimizelyUserContext for the React Native SDK v4+
Describes the useOptimizelyUserContext hook for the React Native 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 Native SDK.
Returns
Returns a UseOptimizelyUserContextResult object — a discriminated union with three possible states:
| State | isLoading | error | userContext |
|---|---|---|---|
| Loading | true | null | null |
| Error | false | Error | null |
| Success | false | null | OptimizelyUserContext |
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 Native SDK are available on GitHub.
Updated 20 days ago
