---
title: useOptimizelyUserContext for the React Native SDK v4+
slug: feature-experimentation/docs/useoptimizely-user-context-for-the-react-native-sdk
createdAt: 2026-08-05T20:39:59.000Z
---

## 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](docId\:Imnygsp94zDIhjj5R7ZEs).

## 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

```javascript
import { Text, TouchableOpacity } from 'react-native';
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 (
    <TouchableOpacity onPress={handlePurchase}>
      <Text>Buy Now</Text>
    </TouchableOpacity>
  );
}
```

## Example — Forced decisions

```javascript
import { Text, TouchableOpacity, View } from 'react-native';
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 (
    <View>
      <TouchableOpacity onPress={forceVariation}>
        <Text>Force Variation A</Text>
      </TouchableOpacity>
      <TouchableOpacity onPress={clearForcedDecisions}>
        <Text>Clear All</Text>
      </TouchableOpacity>
    </View>
  );
}
```

## Source files

The language and platform source files containing the implementation for the React Native SDK are available on [GitHub](https://github.com/optimizely/react-sdk).
