---
title: useOptimizelyUserContext for the React SDK v4+
slug: feature-experimentation/docs/useoptimizely-user-context-for-the-react-sdk
docTags: 
createdAt: 2026-08-05T20:39:54.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 SDK](docId\:rCHtKgccqa7z1Fd5pLkKB).

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

```javascript
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](https://github.com/optimizely/react-sdk).
