> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt
# PostHog React Native SDK
PostHog React Native SDK allows you to capture events and send them to PostHog from your React Native applications.
## Categories
- Initialization
- Identification
- Capture
- Error tracking
- Feature flags
- Group analytics
- Session Replay
- Privacy
- LLM analytics
## PostHog
### Initialization methods
#### PostHogProvider()
**Release Tag:** public
PostHogProvider is a React component that provides PostHog functionality to your React Native app. You can find all configuration options in the [React Native SDK docs](https://posthog.com/docs/libraries/react-native#configuration-options).
Autocapturing navigation requires further configuration. See the [React Native SDK navigation docs](https://posthog.com/docs/libraries/react-native#capturing-screen-views) for more information about autocapturing navigation.
This is the recommended way to set up PostHog for React Native. This utilizes the Context API to pass the PostHog client around, enable autocapture.
### Parameters
- **`{ children, client, options, projectToken, apiKey, autocapture, style, debug, }`** (`any`)
- **`input`** (`PostHogProviderProps`)
### Returns
**Union of:**
- `JSX.Element`
- `null`
### Examples
#### Add to App.(js|ts)
```react-native
// Add to App.(js|ts)
import { usePostHog, PostHogProvider } from 'posthog-react-native'
export function MyApp() {
return (
',
}}>
)
}
// And access the PostHog client via the usePostHog hook
import { usePostHog } from 'posthog-react-native'
const MyComponent = () => {
const posthog = usePostHog()
useEffect(() => {
posthog.capture("event_name")
}, [posthog])
}
```
#### Using with existing client
```react-native
// Using with existing client
import { PostHog } from 'posthog-react-native'
const posthog = new PostHog('', {
host: ''
})
export function MyApp() {
return (
)
}
```
---
#### PostHog()
**Release Tag:** public
Creates a new PostHog instance for React Native. You can find all configuration options in the [React Native SDK docs](https://posthog.com/docs/libraries/react-native#configuration-options).
If you prefer not to use the PostHogProvider, you can initialize PostHog in its own file and import the instance from there.
### Parameters
- **`projectToken`** (`string`) - Your PostHog project token, which starts with `phc_`. Find it in your project settings: https://us.posthog.com/settings/project-details#variables
- **`options?`** (`PostHogOptions`) - PostHog configuration options
### Returns
- `any`
### Examples
```react-native
// posthog.ts
import PostHog from 'posthog-react-native'
export const posthog = new PostHog('', {
host: ''
})
// Then you can access PostHog by importing your instance
// Another file:
import { posthog } from './posthog'
export function MyApp1() {
useEffect(async () => {
posthog.capture('event_name')
}, [posthog])
return Your app code
}
```
---
#### debug()
**Release Tag:** public
Enables or disables debug mode for detailed logging.
**Notes:**
Debug mode logs all PostHog calls to the console for troubleshooting. This is useful during development to understand what data is being sent.
### Parameters
- **`enabled?`** (`boolean`)
### Returns
- `void`
### Examples
#### enable debug mode
```react-native
// enable debug mode
posthog.debug(true)
```
#### disable debug mode
```react-native
// disable debug mode
posthog.debug(false)
```
---
#### shutdown()
**Release Tag:** public
Shuts down the PostHog instance and ensures all events are sent.
Call shutdown() once before the process exits to ensure that all events have been sent and all promises have resolved. Do not use this function if you intend to keep using this PostHog instance after calling it. Use flush() for per-request cleanup instead.
### Parameters
- **`shutdownTimeoutMs?`** (`number`) - Maximum time to wait for shutdown in milliseconds
### Returns
- `Promise`
### Examples
```react-native
// shutdown before process exit
process.on('SIGINT', async () => {
await posthog.shutdown()
process.exit(0)
})
```
---
### Other methods
#### addExceptionStep()
**Release Tag:** public
Records a breadcrumb-style exception step. Steps accumulate in a rolling, byte-bounded buffer and are attached to every captured `$exception` as `$exception_steps`, giving the error tracking UI a timeline of recent activity before each error.
The `$timestamp` is captured at call time. The reserved keys `$message` and `$timestamp` are stripped from `properties` — the SDK sets the canonical values. This method never throws.
### Parameters
- **`message`** (`string`) - A non-empty description of the step
- **`properties?`** (`Properties`) - Optional additional context to attach to the step
### Returns
- `void`
### Examples
```react-native
posthog.addExceptionStep('User tapped Checkout', { screen: 'cart' })
```
---
#### capturePushNotificationOpened()
**Release Tag:** public
Captures `$push_notification_opened` when a user opens a push notification. Requires `@posthog/react-native-plugin`.
Only for taps cannot see itself — local notifications, plus Android taps while the app is running if `@posthog/react-native-plugin` is older than 2.6.0. A notification PostHog sent is still counted once when both paths report it (same `posthog.invocation_id` and action within five minutes); one from another provider is counted twice.
Keys of `payload`'s `posthog` entry become `$notification_` properties. Leave `action` unset for a plain tap; `subtitle` is iOS only. The native SDK builds and sends the event, so JS `before_send` never sees it — redact anything sensitive first.
Not supported on web.
### Parameters
- **`options`** (`{
title?: string;
subtitle?: string;
body?: string;
payload?: {
[key: string]: JsonType;
};
action?: string;
}`)
### Returns
- `Promise`
### Examples
```react-native
// Generated example for capturePushNotificationOpened
posthog.capturePushNotificationOpened();
```
---
#### fetch()
**Release Tag:** public
### Parameters
- **`url`** (`string`)
- **`options`** (`PostHogFetchOptions`)
### Returns
- `Promise`
### Examples
```react-native
// Generated example for fetch
posthog.fetch();
```
---
#### getCommonEventProperties()
**Release Tag:** public
### Returns
- `PostHogEventProperties`
### Examples
```react-native
// Generated example for getCommonEventProperties
posthog.getCommonEventProperties();
```
---
#### getCustomUserAgent()
**Release Tag:** public
### Returns
- `string`
### Examples
```react-native
// Generated example for getCustomUserAgent
posthog.getCustomUserAgent();
```
---
#### getDeviceId()
**Release Tag:** public
Returns the stable device identifier used for device-level feature flag bucketing. This ID persists across identify() and reset() calls, only changing on a fresh app install, manual cache clearing, or OS-initiated storage cleanup.
### Returns
- `string`
### Examples
```react-native
// Generated example for getDeviceId
posthog.getDeviceId();
```
---
#### getLibraryId()
**Release Tag:** public
### Returns
- `string`
### Examples
```react-native
// Generated example for getLibraryId
posthog.getLibraryId();
```
---
#### getLibraryVersion()
**Release Tag:** public
### Returns
- `string`
### Examples
```react-native
// Generated example for getLibraryVersion
posthog.getLibraryVersion();
```
---
#### getPersistedProperty()
**Release Tag:** public
### Parameters
- **`key`** (`PostHogPersistedProperty`)
### Returns
**Union of:**
- `T`
- `undefined`
### Examples
```react-native
// Generated example for getPersistedProperty
posthog.getPersistedProperty();
```
---
#### getSessionId()
**Release Tag:** public
### Returns
- `string`
### Examples
```react-native
// Generated example for getSessionId
posthog.getSessionId();
```
---
#### getSurveyDisplayLanguageOverride()
**Release Tag:** public
### Returns
**Union of:**
- `string`
- `null`
### Examples
```react-native
// Generated example for getSurveyDisplayLanguageOverride
posthog.getSurveyDisplayLanguageOverride();
```
---
#### getSurveys()
**Release Tag:** public
### Returns
- `Promise`
### Examples
```react-native
// Generated example for getSurveys
posthog.getSurveys();
```
---
#### initReactNativeNavigation()
**Release Tag:** public
### Parameters
- **`options`** (`PostHogAutocaptureOptions`)
### Returns
- `boolean`
### Examples
```react-native
// Generated example for initReactNativeNavigation
posthog.initReactNativeNavigation();
```
---
#### registerPushNotificationToken()
**Release Tag:** public
Registers this device's push token so PostHog Workflows can target it. Requires `@posthog/react-native-plugin`.
Registration happens at startup on its own when is on, so call this for token refreshes, which that startup fetch cannot see — on Android only, since a refresh listener yields an FCM token and iOS defaults to APNs. Safe to call before the native SDK is ready; the call queues rather than being dropped.
`appId` says which provider delivers: the Firebase `project_id` for an FCM token, the APNs bundle id for an APNs token. Unset, iOS uses the bundle id and Android the default `FirebaseApp`'s project id, so pass it if you don't use Firebase or use a non-default project. Registration fails server-side if your PostHog project has no matching integration for `appId`.
To use FCM on iOS too, pass the Firebase `project_id` as `appId` and set to `false` first — otherwise the device registers twice (APNs under the bundle id, FCM under the project id), a Workflow with both integrations delivers twice, and clears only the most recent.
Not supported on web or macOS.
### Parameters
- **`deviceToken`** (`string`)
- **`options?`** (`{
appId?: string;
}`)
### Returns
- `Promise`
### Examples
```react-native
// Generated example for registerPushNotificationToken
posthog.registerPushNotificationToken();
```
---
#### resetSessionId()
**Release Tag:** public
### Returns
- `void`
### Examples
```react-native
// Generated example for resetSessionId
posthog.resetSessionId();
```
---
#### setPersistedProperty()
**Release Tag:** public
### Parameters
- **`key`** (`PostHogPersistedProperty`)
- **`value`** (`T | null`)
### Returns
- `void`
### Examples
```react-native
// Generated example for setPersistedProperty
posthog.setPersistedProperty();
```
---
#### unregisterPushNotificationToken()
**Release Tag:** public
Unregisters this device's push token so Workflows stop targeting it — for example from your logout flow. Requires `@posthog/react-native-plugin`.
Durable: a failed or offline request retries on the next flush or launch. `reset()` already moves a registered token to the new identity, so this is only needed if you manage subscriptions yourself.
Not supported on web or macOS.
### Returns
- `Promise`
### Examples
```react-native
// Generated example for unregisterPushNotificationToken
posthog.unregisterPushNotificationToken();
```
---
#### autocapture()
**Release Tag:** public
### Parameters
- **`eventType`** (`string`)
- **`elements`** (`PostHogAutocaptureElement[]`)
- **`properties?`** (`PostHogEventProperties`)
- **`options?`** (`PostHogCaptureOptions`)
### Returns
- `void`
### Examples
```react-native
// Generated example for autocapture
posthog.autocapture();
```
---
#### capture()
**Release Tag:** public
### Parameters
- **`event`** (`string`)
- **`properties?`** (`PostHogEventProperties`)
- **`options?`** (`PostHogCaptureOptions`)
### Returns
- `void`
### Examples
```react-native
// Generated example for capture
posthog.capture();
```
---
#### getAllFeatureFlags()
**Release Tag:** public
Returns all currently cached feature flags as `FeatureFlagResult`s. This is a synchronous read of the flags from the last load (no network request) and does not send a `$feature_flag_called` event.
### Returns
- `FeatureFlagResult[]`
### Examples
```react-native
// Generated example for getAllFeatureFlags
posthog.getAllFeatureFlags();
```
---
#### getFeatureFlagDetails()
**Release Tag:** public
### Returns
**Union of:**
- `PostHogFeatureFlagDetails`
- `undefined`
### Examples
```react-native
// Generated example for getFeatureFlagDetails
posthog.getFeatureFlagDetails();
```
---
#### getFeatureFlagPayloads()
**Release Tag:** deprecated
Returns the payload of every loaded flag, keyed by flag key.
### Returns
**Union of:**
- `PostHogFlagsResponse['featureFlagPayloads']`
- `undefined`
### Examples
```react-native
// Generated example for getFeatureFlagPayloads
posthog.getFeatureFlagPayloads();
```
---
#### getFeatureFlagResult()
**Release Tag:** public
Returns the current evaluation result for a feature flag. `enabled: false` is a conclusive off result; `undefined` means no evaluation is available for the key.
### Parameters
- **`key`** (`string`)
- **`options?`** (`FeatureFlagResultOptions`)
### Returns
**Union of:**
- `FeatureFlagResult`
- `undefined`
### Examples
```react-native
// Generated example for getFeatureFlagResult
posthog.getFeatureFlagResult();
```
---
#### getFeatureFlags()
**Release Tag:** deprecated
Returns the value of every loaded flag, keyed by flag key.
### Returns
**Union of:**
- `PostHogFlagsResponse['featureFlags']`
- `undefined`
### Examples
```react-native
// Generated example for getFeatureFlags
posthog.getFeatureFlags();
```
---
#### getFeatureFlagsAndPayloads()
**Release Tag:** deprecated
Returns the values and payloads of every loaded flag, as two maps keyed by flag key.
### Returns
**Union of:**
- `{
flags: PostHogFlagsResponse['featureFlags']`
- `undefined;
payloads: PostHogFlagsResponse['featureFlagPayloads']`
- `undefined;
}`
### Examples
```react-native
// Generated example for getFeatureFlagsAndPayloads
posthog.getFeatureFlagsAndPayloads();
```
---
#### groupIdentify()
**Release Tag:** public
### Parameters
- **`groupType`** (`string`)
- **`groupKey`** (`string | number`)
- **`groupProperties?`** (`PostHogEventProperties`)
- **`options?`** (`PostHogCaptureOptions`)
### Returns
- `void`
### Examples
```react-native
// Generated example for groupIdentify
posthog.groupIdentify();
```
---
#### groups()
**Release Tag:** public
* ** GROUPS *
### Parameters
- **`groups`** (`PostHogGroupProperties`)
### Returns
- `void`
### Examples
```react-native
// Generated example for groups
posthog.groups();
```
---
#### on()
**Release Tag:** public
### Parameters
- **`event`** (`string`)
- **`cb`** (`(...args: any[]) => void`)
### Returns
- `() => void`
### Examples
```react-native
// Generated example for on
posthog.on();
```
---
#### onFeatureFlag()
**Release Tag:** deprecated
Calls `cb` with the flag's value whenever flags load.
### Parameters
- **`key`** (`string`)
- **`cb`** (`(value: FeatureFlagValue) => void`)
### Returns
- `() => void`
### Examples
```react-native
// Generated example for onFeatureFlag
posthog.onFeatureFlag();
```
---
#### onFeatureFlags()
**Release Tag:** public
### Parameters
- **`cb`** (`(flags: PostHogFlagsResponse['featureFlags']) => void`)
### Returns
- `() => void`
### Examples
```react-native
// Generated example for onFeatureFlags
posthog.onFeatureFlags();
```
---
#### overrideFeatureFlag()
**Release Tag:** deprecated
Overrides the values of the given flags locally until cleared with `null`.
### Parameters
- **`flags`** (`PostHogFlagsResponse['featureFlags'] | null`)
### Returns
- `Promise`
### Examples
```react-native
// Generated example for overrideFeatureFlag
posthog.overrideFeatureFlag();
```
---
#### registerForSession()
**Release Tag:** public
### Parameters
- **`properties`** (`PostHogEventProperties`)
### Returns
- `void`
### Examples
```react-native
// Generated example for registerForSession
posthog.registerForSession();
```
---
#### reloadRemoteConfigAsync()
**Release Tag:** public
### Returns
**Union of:**
- `Promise`
### Examples
```react-native
// Generated example for reloadRemoteConfigAsync
posthog.reloadRemoteConfigAsync();
```
---
#### unregisterForSession()
**Release Tag:** public
### Parameters
- **`property`** (`string`)
### Returns
- `void`
### Examples
```react-native
// Generated example for unregisterForSession
posthog.unregisterForSession();
```
---
#### getSurveysStateless()
**Release Tag:** public
* ** SURVEYS *
### Returns
- `Promise`
### Examples
```react-native
// Generated example for getSurveysStateless
posthog.getSurveysStateless();
```
---
### Identification methods
#### alias()
**Release Tag:** public
Assigns an alias to the current user.
Sometimes, you want to assign multiple distinct IDs to a single user. This is helpful when your primary distinct ID is inaccessible. For example, if a distinct ID used on the frontend is not available in your backend.
### Parameters
- **`alias`** (`string`) - The alias to assign to the current user
### Returns
- `void`
### Examples
```react-native
// set alias for current user
posthog.alias('distinct_id')
```
---
#### createPersonProfile()
**Release Tag:** public
Creates a person profile for the current user, if they don't already have one.
This is useful when using `personProfiles: 'identified_only'` mode and you want to explicitly create a profile for an anonymous user before they identify.
If `personProfiles` is 'identified_only' and no profile exists, this will create one. If `personProfiles` is 'never', this will log an error and do nothing. If `personProfiles` is 'always' or a profile already exists, this is a no-op.
### Returns
- `void`
### Examples
```react-native
// Create a person profile for an anonymous user
posthog.createPersonProfile()
```
---
#### getDistinctId()
**Release Tag:** public
Gets the current user's distinct ID.
You may find it helpful to get the current user's distinct ID. For example, to check whether you've already called identify for a user or not. This returns either the ID automatically generated by PostHog or the ID that has been passed by a call to identify().
### Returns
- `string`
### Examples
```react-native
// get current distinct ID
const distinctId = posthog.getDistinctId()
```
---
#### identify()
**Release Tag:** public
Associates events with a specific user. Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify)
### Parameters
- **`distinctId?`** (`string`) - A unique identifier for your user. Typically either their email or database ID.
- **`properties?`** (`PostHogEventProperties`) - Optional dictionary with key:value pairs to set the person properties
- **`options?`** (`PostHogCaptureOptions`) - Optional capture options
### Returns
- `void`
### Examples
#### Basic identify
```react-native
// Basic identify
posthog.identify('distinctID', {
email: 'user@posthog.com',
name: 'My Name'
})
```
#### Using $set and $set_once
```react-native
// Using $set and $set_once
posthog.identify('distinctID', {
$set: {
email: 'user@posthog.com',
name: 'My Name'
},
$set_once: {
date_of_first_log_in: '2024-03-01'
}
})
```
---
#### reset()
**Release Tag:** public
Resets the user's ID and anonymous ID after logout.
To reset the user's ID and anonymous ID, call reset. Usually you would do this right after the user logs out. This also clears all stored super properties and more.
By default (when `propertiesToKeep` is not provided), the app lifecycle properties (`InstalledAppBuild` and `InstalledAppVersion`) are automatically preserved to prevent duplicate "Application Installed" events on the next app launch.
If you pass `propertiesToKeep` explicitly, only the properties you specify will be preserved. To keep the default app lifecycle behavior, include `PostHogPersistedProperty.InstalledAppBuild` and `PostHogPersistedProperty.InstalledAppVersion` in your array.
Note: The event queue (`PostHogPersistedProperty.Queue`) and logs queue (`PostHogPersistedProperty.LogsQueue`) are always preserved regardless of what is passed in `propertiesToKeep`, to ensure in-flight data is not lost.
The project-level remote config (`PostHogPersistedProperty.RemoteConfig`, `PostHogPersistedProperty.SessionReplay`, `PostHogPersistedProperty.Surveys`) is also always preserved — it is not user data — so session replay and surveys keep working after an identity change. The user-specific survey state (`SurveysSeen`, `SurveyLastSeenDate`) is still cleared.
### Parameters
- **`propertiesToKeep?`** (`PostHogPersistedProperty[]`) - Optional array of persisted properties to preserve during reset. When not provided, app lifecycle and device bucketing properties are automatically preserved. When provided, only the specified properties are preserved. The event queue and logs queue are always preserved regardless.
### Returns
- `void`
### Examples
#### reset after logout (preserves app lifecycle properties by default)
```react-native
// reset after logout (preserves app lifecycle properties by default)
posthog.reset()
```
#### reset but keep feature flag overrides and app lifecycle properties
```react-native
// reset but keep feature flag overrides and app lifecycle properties
posthog.reset([
PostHogPersistedProperty.OverrideFeatureFlags,
PostHogPersistedProperty.InstalledAppBuild,
PostHogPersistedProperty.InstalledAppVersion,
])
```
---
#### setPersonProperties()
**Release Tag:** public
Sets properties on the person profile associated with the current `distinct_id`. Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify)
**Notes:**
Updates user properties that are stored with the person profile in PostHog. If `personProfiles` is set to `identified_only` and no profile exists, this will create one.
### Parameters
- **`userPropertiesToSet?`** (`{
[key: string]: JsonType;
}`) - Optional: An object of properties to store about the user. These properties will overwrite any existing values for the same keys.
- **`userPropertiesToSetOnce?`** (`{
[key: string]: JsonType;
}`) - Optional: An object of properties to store about the user. If a property is previously set, this does not override that value.
- **`reloadFeatureFlags?`** (`boolean`) - Whether to reload feature flags after setting the properties. Defaults to true.
### Returns
- `void`
### Examples
#### set user properties
```react-native
// set user properties
posthog.setPersonProperties({
email: 'user@example.com',
plan: 'premium'
})
```
#### set properties with $set_once
```react-native
// set properties with $set_once
posthog.setPersonProperties(
{ name: 'Max Hedgehog' }, // $set properties
{ initial_url: '/blog' } // $set_once properties
)
```
#### set properties without reloading feature flags
```react-native
// set properties without reloading feature flags
posthog.setPersonProperties({ plan: 'premium' }, undefined, false)
```
---
#### unsetPersonProperties()
**Release Tag:** public
Removes properties from the person profile associated with the current `distinct_id`. Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify)
### Parameters
- **`propertyNames`** (`string | string[]`) - The name (or names) of the person properties to remove.
- **`reloadFeatureFlags?`** (`boolean`) - Whether to reload feature flags after removing the properties. Defaults to true.
### Returns
- `void`
### Examples
```react-native
// Generated example for unsetPersonProperties
posthog.unsetPersonProperties();
```
---
#### getAnonymousId()
**Release Tag:** public
Returns the current anonymous ID.
This is the ID assigned to users before they are identified. It's used to track anonymous users and link them to identified users when they sign up.
### Returns
- `string`
### Examples
```react-native
// get the anonymous ID
const anonId = posthog.getAnonymousId()
console.log('Anonymous ID:', anonId)
```
---
### Error tracking methods
#### captureException()
**Release Tag:** public
Capture a caught exception manually
Exceptions also include capture-time `$app_state` (active, background, inactive or extension) on any platform where React Native AppState provides a known value. On iOS and Android, optional `expo-updates` (0.25.0 or newer) adds `$expo_update_id`, `$expo_runtime_version`, `$expo_channel` and `$expo_is_embedded_launch` for enabled updates outside development mode. Unknown values are omitted. These exception-only fields are separate from the static app metadata controlled by `customAppProperties`, including the existing `$app_version` and `$app_build`. Override these fields with `additionalProperties`, or remove them using `before_send`.
### Parameters
- **`error`** (`Error | unknown`) - The error to capture
- **`additionalProperties?`** (`PostHogEventProperties`) - Any additional properties to add to the error event
- **`hint?`** (`CoreErrorTracking.EventHint`)
### Returns
- `void`
### Examples
#### Capture a caught exception
```react-native
// Capture a caught exception
try {
// something that might throw
} catch (error) {
posthog.captureException(error)
}
```
#### With additional properties
```react-native
// With additional properties
posthog.captureException(error, {
customProperty: 'value',
anotherProperty: ['I', 'can be a list'],
...
})
```
---
### Capture methods
#### captureLog()
**Release Tag:** public
Captures a structured log record and sends it to PostHog's logs product (`/i/v1/logs`). Low-level primitive — most callers will prefer `posthog.logger.info(...)` / `.warn(...)` / `.error(...)` etc., which wrap this with a level pre-set.
Records are buffered per-session, rate-limited, batched into OTLP payloads, and flushed on a timer, on AppState change, or when the buffer reaches capacity. Configure flush cadence, rate cap, and a `beforeSend` filter via the `logs` option on `new PostHog(...)`.
Note — naming collision: `posthog.captureLog()` (this method) is the **logs product** API. There is also a separate, pre-existing `sessionReplayConfig.captureLog` boolean that controls whether **session replay** records the device's `console.*` output. The two are unrelated: this method emits structured records to the logs pipeline regardless of whether session replay is on.
### Parameters
- **`options`** (`CaptureLogOptions`) - Log record. `body` is required; `level` defaults to `'info'`. `attributes` are attached as OTLP key-value attributes and will override auto-populated ones (distinctId, sessionId) on key conflict.
### Returns
- `void`
### Examples
```react-native
posthog.captureLog({
body: 'checkout completed',
level: 'info',
attributes: { order_id: 'ord_789', amount_cents: 4999 },
})
```
---
#### flush()
**Release Tag:** public
Manually flushes the event queue.
You can set the number of events in the configuration that should queue before flushing. Setting this to 1 will send events immediately and will use more battery. This is set to 20 by default. You can also manually flush the queue. If a flush is already in progress it returns a promise for the existing flush.
Note: this drains the **events** pipeline only. Logs are flushed via , and drains both before terminating.
### Returns
- `Promise`
### Examples
```react-native
// manually flush the queue
await posthog.flush()
```
---
#### flushLogs()
**Release Tag:** public
Manually flushes the logs queue.
Logs flush automatically on a timer, when the buffer fills, or on AppState change — most apps never need to call this. Use it when you want a synchronous-style hand-off (e.g. before navigating away from a critical screen, in a custom crash handler, or while testing locally).
If a flush is already in progress, both callers join the same in-flight promise — no double-send.
Note: this drains the **logs** pipeline only. Events are flushed via , and drains both before terminating.
### Returns
- `Promise`
### Examples
```react-native
await posthog.flushLogs()
```
---
#### register()
**Release Tag:** public
Registers super properties that are sent with every event.
Super properties are properties associated with events that are set once and then sent with every capture call. They persist across sessions and are stored locally.
### Parameters
- **`properties`** (`PostHogEventProperties`) - An associative array of properties to store about the user
### Returns
- `Promise`
### Examples
```react-native
// register super properties
posthog.register({
'icecream pref': 'vanilla',
team_id: 22,
})
```
---
#### screen()
**Release Tag:** public
Captures a screen view event.
**Notes:**
This function requires a name. You may also pass in an optional properties object. Once initialized, the screen name is registered immediately for subsequent events, including exceptions. During initialization, screen registration and event capture retain their call order. Exceptions use the last recorded screen, not a destination that has not yet been tracked.
### Parameters
- **`name`** (`string`) - The name of the screen
- **`properties?`** (`PostHogEventProperties`) - Optional properties to include with the screen event
- **`options?`** (`PostHogCaptureOptions`) - Optional capture options
### Returns
- `Promise`
### Examples
#### Basic screen capture
```react-native
// Basic screen capture
posthog.screen('dashboard')
```
#### Screen capture with properties
```react-native
// Screen capture with properties
posthog.screen('dashboard', {
background: 'blue',
hero: 'superhog',
})
```
---
#### setAppLanguage()
**Release Tag:** public
Sets the `$app_language` property: the language your app displays, sent with every event.
Default: not set, so events carry no `$app_language`. React Native apps usually translate in JavaScript (for example with i18next), which the SDK can't see, so call this at startup and whenever the language changes. Compare `$locale`, which is the device language.
The value is kept in memory only and survives `reset()`. A `$app_language` you `register()` wins over it. With `@posthog/react-native-plugin` 3.0 or later, events the native SDK captures itself, such as crashes and push opens, carry it too. Call it right after creating the client so a push open that launched the app carries it as well.
### Parameters
- **`language`** (`string | null`) - A BCP 47 language tag, such as `de` or `pt-BR`. `_` is replaced with `-`. Pass `null` or an empty string to stop sending it.
### Returns
- `void`
### Examples
```react-native
// With i18next or react-i18next
posthog.setAppLanguage(i18n.resolvedLanguage)
i18n.on('languageChanged', (language) => posthog.setAppLanguage(language))
// Your own language setting
posthog.setAppLanguage(settings.language) // at startup
posthog.setAppLanguage('de') // when the user picks German
```
---
#### unregister()
**Release Tag:** public
Removes a super property so it won't be sent with future events.
Super Properties are persisted across sessions so you have to explicitly remove them if they are no longer relevant.
### Parameters
- **`property`** (`string`) - The name of the super property to remove
### Returns
- `Promise`
### Examples
```react-native
// remove a super property
posthog.unregister('icecream pref')
```
---
### Feature flags methods
#### getFeatureFlag()
**Release Tag:** public
Gets the value of a feature flag for the current user.
Returns `true` or `false` for an evaluated boolean flag and a string for a multivariate flag. Returns `undefined` before flags load or when loading fails. For backwards compatibility, a missing key can resolve to `false` after a non-empty response is stored; use `getFeatureFlagResult()` to distinguish an unavailable key from a conclusive off result.
Globally inactive flags are omitted from remote responses, so they follow this missing-key behavior rather than carrying an explicit off evaluation.
### Parameters
- **`key`** (`string`) - The feature flag key
- **`options?`** (`FeatureFlagResultOptions`) - Optional per-call settings
### Returns
**Union of:**
- `boolean`
- `string`
- `undefined`
### Examples
```react-native
// get feature flag value
const value = posthog.getFeatureFlag('key-for-your-boolean-flag')
```
---
#### getFeatureFlagPayload()
**Release Tag:** deprecated
Gets the payload of a feature flag for the current user.
Returns JsonType or undefined if not loaded yet or if there was a problem loading.
### Parameters
- **`key`** (`string`) - The feature flag key
### Returns
**Union of:**
- `JsonType`
- `undefined`
### Examples
```react-native
// get feature flag payload
const payload = posthog.getFeatureFlagResult('key-for-your-multivariate-flag')?.payload
```
---
#### isFeatureEnabled()
**Release Tag:** public
Checks if a feature flag is enabled for the current user.
A `false` return value means the SDK resolved the current value as off. If no evaluation is available, this method returns `defaultValue` when provided. Without a default, it returns `undefined` before flags load; for backwards compatibility, a missing key can resolve to `false` after a non-empty response is stored.
Globally inactive flags are omitted from remote responses, so they follow this missing-key behavior rather than carrying an explicit off evaluation.
### Parameters
- **`key`** (`string`) - The feature flag key
- **`options`** (`IsFeatureEnabledOptions & {
defaultValue: boolean;
}`) - Optional per-call settings
### Returns
- `boolean`
### Examples
#### check if feature flag is enabled
```react-native
// check if feature flag is enabled
const isEnabled = posthog.isFeatureEnabled('key-for-your-boolean-flag')
```
#### fall back to false while flags are not loaded
```react-native
// fall back to false while flags are not loaded
const isEnabled = posthog.isFeatureEnabled('key-for-your-boolean-flag', { defaultValue: false })
```
---
#### reloadFeatureFlags()
**Release Tag:** public
Reloads feature flags from the server.
PostHog loads feature flags when instantiated and refreshes whenever methods are called that affect the flag. If you want to manually trigger a refresh, you can call this method.
**Notes:**
When the `disableRemoteFeatureFlags` option is set, this method is a no-op; supply flag values via `updateFlags()` instead.
### Returns
- `void`
### Examples
```react-native
// reload feature flags
posthog.reloadFeatureFlags()
```
---
#### reloadFeatureFlagsAsync()
**Release Tag:** public
Reloads feature flags from the server asynchronously.
PostHog loads feature flags when instantiated and refreshes whenever methods are called that affect the flag. If you want to manually trigger a refresh and get the result, you can call this method.
**Notes:**
When the `disableRemoteFeatureFlags` option is set, no request is made and the promise resolves with the currently stored flags (from `bootstrap` or `updateFlags()`).
### Returns
**Union of:**
- `Promise`
- `undefined>`
### Examples
```react-native
// reload feature flags and get result
posthog.reloadFeatureFlagsAsync().then((refreshedFlags) => console.log(refreshedFlags))
```
---
#### resetGroupPropertiesForFlags()
**Release Tag:** public
Resets group properties for feature flag evaluation.
### Parameters
- **`reloadFeatureFlags?`** (`boolean`) - Whether to reload feature flags after setting the properties. Defaults to true.
### Returns
- `void`
### Examples
```react-native
// reset group properties for flags
posthog.resetGroupPropertiesForFlags()
```
---
#### resetPersonPropertiesForFlags()
**Release Tag:** public
Resets person properties for feature flag evaluation.
### Parameters
- **`reloadFeatureFlags?`** (`boolean`) - Whether to reload feature flags after setting the properties. Defaults to true.
### Returns
- `void`
### Examples
```react-native
// reset person properties for flags
posthog.resetPersonPropertiesForFlags()
```
---
#### setGroupPropertiesForFlags()
**Release Tag:** public
Sets group properties for feature flag evaluation.
These properties are automatically attached to the current group (set via posthog.group()). When you change the group, these properties are reset.
### Parameters
- **`properties`** (`Record>`) - The group properties to set for flag evaluation
- **`reloadFeatureFlags?`** (`boolean`) - Whether to reload feature flags after setting the properties. Defaults to true.
### Returns
- `void`
### Examples
```react-native
// set group properties for flags
posthog.setGroupPropertiesForFlags({'company': {'property1': 'value', property2: 'value2'}})
```
---
#### setPersonPropertiesForFlags()
**Release Tag:** public
Sets person properties for feature flag evaluation.
Sometimes, you might want to evaluate feature flags using properties that haven't been ingested yet, or were set incorrectly earlier. You can do so by setting properties the flag depends on with this call. These are set for the entire session. Successive calls are additive: all properties you set are combined together and sent for flag evaluation.
### Parameters
- **`properties`** (`Record`) - The person properties to set for flag evaluation
- **`reloadFeatureFlags?`** (`boolean`) - Whether to reload feature flags after setting the properties. Defaults to true.
### Returns
- `void`
### Examples
```react-native
// set person properties for flags
posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'})
```
---
#### updateFlags()
**Release Tag:** public
Replaces (or merges into) the stored feature flags and payloads with locally supplied values, exactly as if they had been returned by the flags endpoint: the values are persisted, `getFeatureFlag()`/`getFeatureFlagPayload()` read them back, and `onFeatureFlags` listeners fire. Makes no network request.
Intended for apps that evaluate flags outside the SDK (e.g. server-side local evaluation) and push the results in at runtime, typically together with the `disableRemoteFeatureFlags` option so the SDK never fetches flags itself.
**Notes:**
The values are cleared by `reset()`, so push them again after an identity change.
### Parameters
- **`flags`** (`Record`) - Flag keys mapped to their values (boolean, or a variant string)
- **`payloads?`** (`Record`) - Optional flag keys mapped to their JSON payloads
- **`options?`** (`{
merge?: boolean;
}`) - Set `merge: true` to merge with the currently stored flags instead of replacing them
### Returns
- `void`
### Examples
#### replace all stored flags with locally evaluated ones
```react-native
// replace all stored flags with locally evaluated ones
posthog.updateFlags({ 'my-flag': true, 'multivariate-flag': 'variant-1' })
```
#### include payloads
```react-native
// include payloads
posthog.updateFlags({ 'my-flag': true }, { 'my-flag': { color: 'blue' } })
```
#### merge into the stored flags instead of replacing them
```react-native
// merge into the stored flags instead of replacing them
posthog.updateFlags({ 'my-flag': false }, undefined, { merge: true })
```
---
### Group analytics methods
#### group()
**Release Tag:** public
Associates the current user with a group.
Group analytics allows you to associate the events for that person's session with a group (e.g. teams, organizations, etc.). This is a paid feature and is not available on the open-source or free cloud plan.
### Parameters
- **`groupType`** (`string`) - The type of group (e.g. 'company', 'team')
- **`groupKey`** (`string`) - The unique identifier for the group
- **`properties?`** (`PostHogEventProperties`) - Optional properties to set for the group
### Returns
- `void`
### Examples
#### associate with a group
```react-native
// associate with a group
posthog.group('company', 'company_id_in_your_db')
```
#### associate with a group and update properties
```react-native
// associate with a group and update properties
posthog.group('company', 'company_id_in_your_db', {
name: 'Awesome Inc.',
employees: 11,
})
```
---
### Session Replay methods
#### isSessionReplayActive()
**Release Tag:** public
Returns whether session replay is currently active.
Note: This is only available on iOS and Android. On web/macOS, this always returns false.
### Returns
- `Promise`
### Examples
```react-native
const isActive = await posthog.isSessionReplayActive()
```
---
#### startSessionRecording()
**Release Tag:** public
Starts session recording. This method will have no effect if PostHog is not enabled, or if session replay is disabled in your project settings.
A refused manual start is retried with successive delays of 1, 2, 4, 8, and 16 seconds, and on subsequent feature flags loads while pending. This promise resolves after the initial attempt, without waiting for retries or guaranteeing recording is active. A newer start supersedes an unfinished request. Stop, reset, opt-out, and shutdown cancel pending starts. Use `isSessionReplayActive()` to check the current recording state.
Note: This is only available on iOS and Android. On web/macOS, this is a no-op.
Requires `posthog-react-native-session-replay` version 1.3.0 or higher.
### Parameters
- **`resumeCurrent?`** (`boolean`) - Whether to resume recording of current session (true) or start a new session (false). Defaults to true.
### Returns
- `Promise`
### Examples
#### Resume the current session recording
```react-native
// Resume the current session recording
await posthog.startSessionRecording()
```
#### Start a new session recording
```react-native
// Start a new session recording
await posthog.startSessionRecording(false)
```
---
#### stopSessionRecording()
**Release Tag:** public
Stops the current session recording if one is in progress.
Note: This is only available on iOS and Android. On web/macOS, this is a no-op.
Requires `posthog-react-native-session-replay` version 1.3.0 or higher.
### Returns
- `Promise`
### Examples
```react-native
await posthog.stopSessionRecording()
```
---
### Privacy methods
#### optIn()
**Release Tag:** public
Opts the user in to data capture.
By default, PostHog has tracking enabled unless it is forcefully disabled by default using the option defaultOptIn: false . Once this has been called it is persisted and will be respected until optOut is called again or the reset function is called. When opting in after an opt-out, session replay restarts in a new session if the app wanted it on at opt-out: `enableSessionReplay` is on, or the app called `startSessionRecording()`, and the app has not called `stopSessionRecording()` since. This holds even if replay was not recording at opt-out, for example while it waited for the linked flag or an event trigger. The linked flag, sampling and event triggers apply to the restart as usual. The promise resolves once session replay has been re-evaluated. A `startSessionRecording()` or `stopSessionRecording()` call made while opted out does not change this; to keep replay stopped, call `stopSessionRecording()` before `optOut()` or after `optIn()`.
### Returns
- `Promise`
### Examples
```react-native
// opt in to tracking
posthog.optIn()
```
---
#### optOut()
**Release Tag:** public
Opts the user out of data capture.
You can completely opt-out users from data capture. Once this has been called it is persisted and will be respected until optIn is called again or the reset function is called. The promise resolves once session replay has stopped.
### Returns
- `Promise`
### Examples
```react-native
// opt out of tracking
posthog.optOut()
```
---
### LLM analytics methods
#### captureTraceFeedback()
**Release Tag:** public
Capture written user feedback for a LLM trace. Numeric values are converted to strings.
### Parameters
- **`traceId`** (`string | number`) - The trace ID to capture feedback for.
- **`userFeedback`** (`string`) - The feedback to capture.
### Returns
- `void`
### Examples
```react-native
// Generated example for captureTraceFeedback
posthog.captureTraceFeedback();
```
---
#### captureTraceMetric()
**Release Tag:** public
Capture a metric for a LLM trace. Numeric values are converted to strings.
### Parameters
- **`traceId`** (`string | number`) - The trace ID to capture the metric for.
- **`metricName`** (`string`) - The name of the metric to capture.
- **`metricValue`** (`string | number | boolean`) - The value of the metric to capture.
### Returns
- `void`
### Examples
```react-native
// Generated example for captureTraceMetric
posthog.captureTraceMetric();
```
---