PostHog React Native SDK

SDK Version: 4.5.1

PostHog

Initialization methods

PostHogProviderpublic

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.

Autocapturing navigation requires further configuration. See the React Native SDK navigation docs 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

NameType
{ children, client, options, apiKey, autocapture, style, debug, }PostHogProviderProps

Examples

JSX
// Add to App.(js|ts)
import { usePostHog, PostHogProvider } from 'posthog-react-native'
export function MyApp() {
return (
<PostHogProvider apiKey="<ph_project_api_key>" options={{
host: 'https://us.i.posthog.com',
}}>
<MyComponent />
</PostHogProvider>
)
}
// 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])
}

Returns

Type
Union ofJSX.Element
null

PostHogpublic

Creates a new PostHog instance for React Native. You can find all configuration options in the React Native SDK docs.

If you prefer not to use the PostHogProvider, you can initialize PostHog in its own file and import the instance from there.

Parameters

NameType
apiKeystring

Your PostHog API key

options?PostHogOptions

PostHog configuration options

Examples

JSX
// posthog.ts
import PostHog from 'posthog-react-native'
export const posthog = new PostHog('<ph_project_api_key>', {
host: 'https://us.i.posthog.com'
})
// 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 <View>Your app code</View>
}

Returns

Type
any

debugpublic

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

NameType
enabled?boolean

Examples

JSX
// enable debug mode
posthog.debug(true)

Returns

Type
void

shutdownpublic

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

NameType
shutdownTimeoutMs?number

Maximum time to wait for shutdown in milliseconds

Examples

JSX
// shutdown before process exit
process.on('SIGINT', async () => {
await posthog.shutdown()
process.exit(0)
})

Returns

Type
Promise<void>

Capture methods

flushpublic

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.

Examples

JSX
// manually flush the queue
await posthog.flush()

Returns

Type
Promise<void>

registerpublic

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

NameType
propertiesPostHogEventProperties

An associative array of properties to store about the user

Examples

JSX
// register super properties
posthog.register({
'icecream pref': 'vanilla',
team_id: 22,
})

Returns

Type
Promise<void>

screenpublic

Captures a screen view event.

Notes:

This function requires a name. You may also pass in an optional properties object. Screen name is automatically registered for the session and will be included in subsequent events.

Parameters

NameType
namestring

The name of the screen

properties?PostHogEventProperties

Optional properties to include with the screen event

options?PostHogCaptureOptions

Optional capture options

Examples

JSX
// Basic screen capture
posthog.screen('dashboard')

Returns

Type
Promise<void>

unregisterpublic

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

NameType
propertystring

The name of the super property to remove

Examples

JSX
// remove a super property
posthog.unregister('icecream pref')

Returns

Type
Promise<void>

Error tracking methods

captureExceptionpublic

Capture a caught exception manually

Parameters

NameType
errorunknown

The error to capture

additionalProperties?PostHogEventProperties

Any additional properties to add to the error event

Examples

JSX
// Capture a caught exception
try {
// something that might throw
} catch (error) {
posthog.captureException(error)
}

Returns

Type
void

Feature flags methods

getFeatureFlagpublic

Gets the value of a feature flag for the current user.

Defaults to undefined if not loaded yet or if there was a problem loading. Multivariant feature flags are returned as a string.

Parameters

NameType
keystring

The feature flag key

Examples

JSX
// get feature flag value
const value = posthog.getFeatureFlag('key-for-your-boolean-flag')

Returns

Type
Union ofboolean
string
undefined

getFeatureFlagPayloadpublic

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

NameType
keystring

The feature flag key

Examples

JSX
// get feature flag payload
const payload = posthog.getFeatureFlagPayload('key-for-your-multivariate-flag')

Returns

Type
Union ofJsonType
undefined

isFeatureEnabledpublic

Checks if a feature flag is enabled for the current user.

Defaults to undefined if not loaded yet or if there was a problem loading.

Parameters

NameType
keystring

The feature flag key

Examples

JSX
// check if feature flag is enabled
const isEnabled = posthog.isFeatureEnabled('key-for-your-boolean-flag')

Returns

Type
Union ofboolean
undefined

reloadFeatureFlagspublic

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.

Examples

JSX
// reload feature flags
posthog.reloadFeatureFlags()

Returns

Type
void

reloadFeatureFlagsAsyncpublic

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.

Examples

JSX
// reload feature flags and get result
posthog.reloadFeatureFlagsAsync().then((refreshedFlags) => console.log(refreshedFlags))

Returns

Type
Union ofPromise<Record<string, boolean
string>
undefined>

resetGroupPropertiesForFlagspublic

Resets group properties for feature flag evaluation.

Examples

JSX
// reset group properties for flags
posthog.resetGroupPropertiesForFlags()

Returns

Type
void

resetPersonPropertiesForFlagspublic

Resets person properties for feature flag evaluation.

Examples

JSX
// reset person properties for flags
posthog.resetPersonPropertiesForFlags()

Returns

Type
void

setGroupPropertiesForFlagspublic

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

NameType
propertiesRecord<string, Record<string, string>>

The group properties to set for flag evaluation

Examples

JSX
// set group properties for flags
posthog.setGroupPropertiesForFlags({'company': {'property1': 'value', property2: 'value2'}})

Returns

Type
void

setPersonPropertiesForFlagspublic

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

NameType
propertiesRecord<string, string>

The person properties to set for flag evaluation

Examples

JSX
// set person properties for flags
posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'})

Returns

Type
void

Group analytics methods

grouppublic

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

NameType
groupTypestring

The type of group (e.g. 'company', 'team')

groupKeystring

The unique identifier for the group

properties?PostHogEventProperties

Optional properties to set for the group

Examples

JSX
// associate with a group
posthog.group('company', 'company_id_in_your_db')

Returns

Type
void

Identification methods

aliaspublic

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

NameType
aliasstring

The alias to assign to the current user

Examples

JSX
// set alias for current user
posthog.alias('distinct_id')

Returns

Type
void

getDistinctIdpublic

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().

Examples

JSX
// get current distinct ID
const distinctId = posthog.getDistinctId()

Returns

Type
string

identifypublic

Associates events with a specific user. Learn more about identifying users

Parameters

NameType
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

Examples

JSX
// Basic identify
posthog.identify('distinctID', {
email: 'user@posthog.com',
name: 'My Name'
})

Returns

Type
void

resetpublic

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.

Examples

JSX
// reset after logout
posthog.reset()

Returns

Type
void

getAnonymousIdpublic

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.

Examples

JSX
// get the anonymous ID
const anonId = posthog.getAnonymousId()
console.log('Anonymous ID:', anonId)

Returns

Type
string

LLM analytics methods

captureTraceFeedbackpublic

Capture written user feedback for a LLM trace. Numeric values are converted to strings.

Parameters

NameType
traceIdstring | number

The trace ID to capture feedback for.

userFeedbackstring

The feedback to capture.

Examples

JSX
// Generated example for captureTraceFeedback
posthog.captureTraceFeedback();

Returns

Type
void

captureTraceMetricpublic

Capture a metric for a LLM trace. Numeric values are converted to strings.

Parameters

NameType
traceIdstring | number

The trace ID to capture the metric for.

metricNamestring

The name of the metric to capture.

metricValuestring | number | boolean

The value of the metric to capture.

Examples

JSX
// Generated example for captureTraceMetric
posthog.captureTraceMetric();

Returns

Type
void

Privacy methods

optInpublic

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.

Examples

JSX
// opt in to tracking
posthog.optIn()

Returns

Type
Promise<void>

optOutpublic

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.

Examples

JSX
// opt out of tracking
posthog.optOut()

Returns

Type
Promise<void>

Other methods

fetchpublic

Parameters

NameType
urlstring
optionsPostHogFetchOptions

Examples

JSX
// Generated example for fetch
posthog.fetch();

Returns

getCommonEventPropertiespublic

Examples

JSX
// Generated example for getCommonEventProperties
posthog.getCommonEventProperties();

getCustomUserAgentpublic

Examples

JSX
// Generated example for getCustomUserAgent
posthog.getCustomUserAgent();

Returns

Type
string

getLibraryIdpublic

Examples

JSX
// Generated example for getLibraryId
posthog.getLibraryId();

Returns

Type
string

getLibraryVersionpublic

Examples

JSX
// Generated example for getLibraryVersion
posthog.getLibraryVersion();

Returns

Type
string

getPersistedPropertypublic

Parameters

Examples

JSX
// Generated example for getPersistedProperty
posthog.getPersistedProperty();

Returns

Type
Union ofT
undefined

getSessionIdpublic

Examples

JSX
// Generated example for getSessionId
posthog.getSessionId();

Returns

Type
string

getSurveyspublic

Examples

JSX
// Generated example for getSurveys
posthog.getSurveys();

Returns

Type
Promise<SurveyResponse['surveys']>

initReactNativeNavigationpublic

Parameters

Examples

JSX
// Generated example for initReactNativeNavigation
posthog.initReactNativeNavigation();

Returns

Type
boolean

resetSessionIdpublic

Examples

JSX
// Generated example for resetSessionId
posthog.resetSessionId();

Returns

Type
void

setPersistedPropertypublic

Parameters

NameType
keyPostHogPersistedProperty
valueT | null

Examples

JSX
// Generated example for setPersistedProperty
posthog.setPersistedProperty();

Returns

Type
void

autocapturepublic

Parameters

NameType
eventTypestring
elementsPostHogAutocaptureElement[]
properties?PostHogEventProperties
options?PostHogCaptureOptions

Examples

JSX
// Generated example for autocapture
posthog.autocapture();

Returns

Type
void

capturepublic

Parameters

NameType
eventstring
properties?PostHogEventProperties
options?PostHogCaptureOptions

Examples

JSX
// Generated example for capture
posthog.capture();

Returns

Type
void

getFeatureFlagDetailspublic

Examples

JSX
// Generated example for getFeatureFlagDetails
posthog.getFeatureFlagDetails();

Returns

Type
Union ofPostHogFeatureFlagDetails
undefined

getFeatureFlagPayloadspublic

Examples

JSX
// Generated example for getFeatureFlagPayloads
posthog.getFeatureFlagPayloads();

Returns

Type
Union ofPostHogFlagsResponse['featureFlagPayloads']
undefined

getFeatureFlagspublic

Examples

JSX
// Generated example for getFeatureFlags
posthog.getFeatureFlags();

Returns

Type
Union ofPostHogFlagsResponse['featureFlags']
undefined

getFeatureFlagsAndPayloadspublic

Examples

JSX
// Generated example for getFeatureFlagsAndPayloads
posthog.getFeatureFlagsAndPayloads();

Returns

Type
Union of{ flags: PostHogFlagsResponse['featureFlags']
undefined; payloads: PostHogFlagsResponse['featureFlagPayloads']
undefined; }

getKnownFeatureFlagspublic

Examples

JSX
// Generated example for getKnownFeatureFlags
posthog.getKnownFeatureFlags();

Returns

Type
Union ofPostHogFlagsResponse['featureFlags']
undefined

groupIdentifypublic

Parameters

NameType
groupTypestring
groupKeystring | number
groupProperties?PostHogEventProperties
options?PostHogCaptureOptions

Examples

JSX
// Generated example for groupIdentify
posthog.groupIdentify();

Returns

Type
void

groupspublic

  • ** GROUPS *

Parameters

Examples

JSX
// Generated example for groups
posthog.groups();

Returns

Type
void

onpublic

Parameters

NameType
eventstring
cb(...args: any[]) => void

Examples

JSX
// Generated example for on
posthog.on();

Returns

Type
() => void

onFeatureFlagpublic

Parameters

NameType
keystring
cb(value: FeatureFlagValue) => void

Examples

JSX
// Generated example for onFeatureFlag
posthog.onFeatureFlag();

Returns

Type
() => void

onFeatureFlagspublic

Parameters

NameType
cb(flags: PostHogFlagsResponse['featureFlags']) => void

Examples

JSX
// Generated example for onFeatureFlags
posthog.onFeatureFlags();

Returns

Type
() => void

overrideFeatureFlagpublic

Parameters

NameType
flagsPostHogFlagsResponse['featureFlags'] | null

Examples

JSX
// Generated example for overrideFeatureFlag
posthog.overrideFeatureFlag();

Returns

Type
Promise<void>

registerForSessionpublic

Parameters

NameType
propertiesPostHogEventProperties

Examples

JSX
// Generated example for registerForSession
posthog.registerForSession();

Returns

Type
void

reloadRemoteConfigAsyncpublic

Examples

JSX
// Generated example for reloadRemoteConfigAsync
posthog.reloadRemoteConfigAsync();

Returns

Type
Union ofPromise<PostHogRemoteConfig
undefined>

setupBootstrappublic

Parameters

NameType
options?Partial<PostHogCoreOptions>

Examples

JSX
// Generated example for setupBootstrap
posthog.setupBootstrap();

Returns

Type
void

unregisterForSessionpublic

Parameters

NameType
propertystring

Examples

JSX
// Generated example for unregisterForSession
posthog.unregisterForSession();

Returns

Type
void

addPendingPromisepublic

Parameters

NameType
promisePromise<T>

Examples

JSX
// Generated example for addPendingPromise
posthog.addPendingPromise();

Returns

Type
Promise<T>

aliasStatelesspublic

Parameters

NameType
aliasstring
distinctIdstring
properties?PostHogEventProperties
options?PostHogCaptureOptions

Examples

JSX
// Generated example for aliasStateless
posthog.aliasStateless();

Returns

Type
void

aliasStatelessImmediatepublic

Parameters

NameType
aliasstring
distinctIdstring
properties?PostHogEventProperties
options?PostHogCaptureOptions

Examples

JSX
// Generated example for aliasStatelessImmediate
posthog.aliasStatelessImmediate();

Returns

Type
Promise<void>

captureStatelesspublic

Parameters

NameType
distinctIdstring
eventstring
properties?PostHogEventProperties
options?PostHogCaptureOptions

Examples

JSX
// Generated example for captureStateless
posthog.captureStateless();

Returns

Type
void

captureStatelessImmediatepublic

Parameters

NameType
distinctIdstring
eventstring
properties?PostHogEventProperties
options?PostHogCaptureOptions

Examples

JSX
// Generated example for captureStatelessImmediate
posthog.captureStatelessImmediate();

Returns

Type
Promise<void>

enqueuepublic

  • ** QUEUEING AND FLUSHING *

Parameters

NameType
typestring
_messageany
options?PostHogCaptureOptions

Examples

JSX
// Generated example for enqueue
posthog.enqueue();

Returns

Type
void

getCustomHeaderspublic

Examples

JSX
// Generated example for getCustomHeaders
posthog.getCustomHeaders();

Returns

Type
{ [key: string]: string; }

getFeatureFlagDetailsStatelesspublic

Parameters

NameType
distinctIdstring
groups?Record<string, string | number>
personProperties?Record<string, string>
groupProperties?Record<string, Record<string, string>>
disableGeoip?boolean
flagKeysToEvaluate?string[]

Examples

JSX
// Generated example for getFeatureFlagDetailsStateless
posthog.getFeatureFlagDetailsStateless();

Returns

Type
Union ofPromise<PostHogFeatureFlagDetails
undefined>

getFeatureFlagDetailStatelesspublic

Parameters

NameType
keystring
distinctIdstring
groups?Record<string, string>
personProperties?Record<string, string>
groupProperties?Record<string, Record<string, string>>
disableGeoip?boolean

Examples

JSX
// Generated example for getFeatureFlagDetailStateless
posthog.getFeatureFlagDetailStateless();

Returns

Type
Union ofPromise<{ response: FeatureFlagDetail
undefined; requestId: string
undefined; }
undefined>

getFeatureFlagPayloadsStatelesspublic

Parameters

NameType
distinctIdstring
groups?Record<string, string>
personProperties?Record<string, string>
groupProperties?Record<string, Record<string, string>>
disableGeoip?boolean
flagKeysToEvaluate?string[]

Examples

JSX
// Generated example for getFeatureFlagPayloadsStateless
posthog.getFeatureFlagPayloadsStateless();

Returns

Type
Union ofPromise<PostHogFlagsResponse['featureFlagPayloads']
undefined>

getFeatureFlagPayloadStatelesspublic

Parameters

NameType
keystring
distinctIdstring
groups?Record<string, string>
personProperties?Record<string, string>
groupProperties?Record<string, Record<string, string>>
disableGeoip?boolean

Examples

JSX
// Generated example for getFeatureFlagPayloadStateless
posthog.getFeatureFlagPayloadStateless();

Returns

Type
Union ofPromise<JsonType
undefined>

getFeatureFlagsAndPayloadsStatelesspublic

Parameters

NameType
distinctIdstring
groups?Record<string, string | number>
personProperties?Record<string, string>
groupProperties?Record<string, Record<string, string>>
disableGeoip?boolean
flagKeysToEvaluate?string[]

Examples

JSX
// Generated example for getFeatureFlagsAndPayloadsStateless
posthog.getFeatureFlagsAndPayloadsStateless();

Returns

Type
Union ofPromise<{ flags: PostHogFlagsResponse['featureFlags']
undefined; payloads: PostHogFlagsResponse['featureFlagPayloads']
undefined; requestId: PostHogFlagsResponse['requestId']
undefined; }>

getFeatureFlagsStatelesspublic

Parameters

NameType
distinctIdstring
groups?Record<string, string | number>
personProperties?Record<string, string>
groupProperties?Record<string, Record<string, string>>
disableGeoip?boolean
flagKeysToEvaluate?string[]

Examples

JSX
// Generated example for getFeatureFlagsStateless
posthog.getFeatureFlagsStateless();

Returns

Type
Union ofPromise<{ flags: PostHogFlagsResponse['featureFlags']
undefined; payloads: PostHogFlagsResponse['featureFlagPayloads']
undefined; requestId: PostHogFlagsResponse['requestId']
undefined; }>

getFeatureFlagStatelesspublic

Parameters

NameType
keystring
distinctIdstring
groups?Record<string, string>
personProperties?Record<string, string>
groupProperties?Record<string, Record<string, string>>
disableGeoip?boolean

Examples

JSX
// Generated example for getFeatureFlagStateless
posthog.getFeatureFlagStateless();

Returns

Type
Union ofPromise<{ response: FeatureFlagValue
undefined; requestId: string
undefined; }>

getFlagspublic

  • ** FEATURE FLAGS *

Parameters

NameType
distinctIdstring
groups?Record<string, string | number>
personProperties?Record<string, string>
groupProperties?Record<string, Record<string, string>>
extraPayload?Record<string, any>

Examples

JSX
// Generated example for getFlags
posthog.getFlags();

Returns

Type
Union ofPromise<PostHogFlagsResponse
undefined>

getRemoteConfigpublic

Examples

JSX
// Generated example for getRemoteConfig
posthog.getRemoteConfig();

Returns

Type
Union ofPromise<PostHogRemoteConfig
undefined>

getSurveysStatelesspublic

  • ** SURVEYS *

Examples

JSX
// Generated example for getSurveysStateless
posthog.getSurveysStateless();

Returns

Type
Promise<SurveyResponse['surveys']>

groupIdentifyStatelesspublic

  • ** GROUPS *

Parameters

NameType
groupTypestring
groupKeystring | number
groupProperties?PostHogEventProperties
options?PostHogCaptureOptions
distinctId?string
eventProperties?PostHogEventProperties

Examples

JSX
// Generated example for groupIdentifyStateless
posthog.groupIdentifyStateless();

Returns

Type
void

identifyStatelesspublic

  • ** TRACKING *

Parameters

NameType
distinctIdstring
properties?PostHogEventProperties
options?PostHogCaptureOptions

Examples

JSX
// Generated example for identifyStateless
posthog.identifyStateless();

Returns

Type
void

identifyStatelessImmediatepublic

Parameters

NameType
distinctIdstring
properties?PostHogEventProperties
options?PostHogCaptureOptions

Examples

JSX
// Generated example for identifyStatelessImmediate
posthog.identifyStatelessImmediate();

Returns

Type
Promise<void>

logMsgIfDebugpublic

Parameters

NameType
fn() => void

Examples

JSX
// Generated example for logMsgIfDebug
posthog.logMsgIfDebug();

Returns

Type
void

sendImmediatepublic

Parameters

NameType
typestring
_messageany
options?PostHogCaptureOptions

Examples

JSX
// Generated example for sendImmediate
posthog.sendImmediate();

Returns

Type
Promise<void>

wrappublic

Parameters

NameType
fn() => void

Examples

JSX
// Generated example for wrap
posthog.wrap();

Returns

Type
void

Community questions

Questions about this page? or post a community question.