React Native SDK Reference

This is a reference guide for all React Native SDK requirements, known limitations, API reference, and performance impact information.

The React Native SDK artifacts are distributed through NPM.

For notes on the latest SDK versions, see our React Native changelog.

❗️

If you're using Heap's Classic React Native SDK and thinking about switching to our newest offerings, please note that some events might need to be repaired after upgrade. Be sure to check out the full breakdown of the differences between our SDKs here.

Need help with this process? Please post in Community or contact us via the Get support page in Heap.

📘

This reference is exclusive to Heap's current Android SDK. For information about Heap's Classic Android SDK, you can visit its documentation.

Heap React Native Bridge Reference

Requirements + Known Limitations

  • This SDK requires React Native 0.63 or later.
    • For Android, the SDK requires Android API level 16 or higher.
    • For iOS, the SDK requires iOS 12 or later.
  • The SDK depends on native modules and won't capture events in the Expo Go app. To test Heap on an Expo app, you'll need to eject the app first and test with the product.

API Reference

Heap

  • Import: import { Heap } from '@heap/heap-react-native-bridge';

The public-facing API for the Heap React Native Bridge SDK.

startRecording(environmentId: string, options?: Options)

Description
Initializes the Heap SDK and enables Heap to start recording data.

If Heap is already recording and the options have changed, Heap will restart tracking with the new options, creating a new session. Otherwise, calling this method multiple times with the same value has no effect.

Parameters

  • environmentId: The environment ID to which data should be attributed.
  • options: (optional) A dictionary of configuration options for use starting the SDK. See React Native Custom Configuration for available options.

Examples

import { Heap } from '@heap/heap-react-native-bridge';

Heap.startRecording("YOUR_APP_ID");

Heap.startRecording("YOUR_APP_ID", {
  uploadInterval: 60,
});

stopRecording()

Description
Shuts down the Heap SDK and prevents any further data collection.

Examples

import { Heap } from '@heap/heap-react-native-bridge';

Heap.stopRecording();

track(event: string, properties?: Properties | null, timestamp?: Date | null, sourceInfo?: SourceInfo | null, pageview?: Pageview | 'none' | null)

Description
Creates an event message to be tracked and sent to the Heap API.

Parameters

  • event: The string name of the event.
  • properties (optional): A Record<string, number | string | boolean | bigint> containing properties to associate with the event.
  • timestamp (optional): The Date of when the event occurs. Defaults to the current time. Customer implementations shouldn't assign values for this parameter.
  • sourceInfo (optional): The nullable SourceInfo object if this event was generated by an autocapture SDK. Defaults to null. Customer implementations shouldn't assign values for this parameter.
  • pageview (optional): The Pageview to associate with the tracked event. This is most commonly the case if the event was generated by an autocapture SDK. Defaults to null. Customer implementations shouldn't assign values for this parameter.

Examples

import { Heap } from '@heap/heap-react-native-bridge';

// Without properties
Heap.track("Added to cart");

// With properties
Heap.track("Added to cart", {
  product_category: product.category,
});

identify(identity: string)

Description
Assigns an identity to be associated with the current user ID, used for combining users across multiple implementations.

If the identity is already set and it is different from the past identity, this will reset the user ID and session while setting the identity.

Parameters

  • identity: The string value representing the identity to associate with events. This should uniquely identify the person using the app, and never be a hard-coded value.

Examples
In this example, the app has a method userAuthenticated which is called when the user logs into the app.

import { Heap } from '@heap/heap-react-native-bridge';

Heap.identify("some_identity")

resetIdentity()

Description
Resets the state for a user that was previously identified with identify, creating a new user and session while clearing event properties. If the user wasn't previously identified, this method has no effect.

Examples
In this example, the app has a method userLoggedOut which is called when the user logs out of the app.

import { Heap } from '@heap/heap-react-native-bridge';

const userLoggedOut = () => {
  ...
  Heap.resetIdentity();
};

addUserProperties(properties: Properties)

Description
Add a collection of properties to be associated with the current user.

Parameters

  • properties: A Record<string, number | string | boolean | bigint> containing properties to associate with the user.

Examples
In this example, the app has a method userAuthenticated which is called when the user logs into the app.

import { Heap } from '@heap/heap-react-native-bridge';

const userAuthenticated = (user: AppUser) => {
  ...
  Heap.addUserProperties({
    membership_tier: user.membershipTier,
    team_name: user.team.name,
  });
}

addEventProperties(properties: Properties)

Description
Add a collection of properties to be associated with all future events from the current user.

Parameters

  • properties: A Record<string, number | string | boolean | bigint> containing properties to associate with future events.

Examples
In this example, the app has a method contentLoaded which is called when a view loads data and we want to group future events based on the hero banner that was displayed.

import { Heap } from '@heap/heap-react-native-bridge';

const contentLoaded = (content: HomeScreenContent) => {
  ...
  const heroName = content.hero?.name;
  if (heroName) {
    Heap.addEventProperties({
      home_screen_hero: heroName,
    });
  }
};

removeEventProperty(name: string)

Description
Removes a single event-wide property that was previously added with addEventProperties.

Parameters

  • event: The string name of the event.

Examples
In this example, we want to track a property on all events while a component is on screen:

import { Heap } from '@heap/heap-react-native-bridge';

useEffect(() => {
  if (chatPopupVisible) {
    Heap.addEventProperties({
      chat_popup_is_visible: true,
    });
  } else {
    Heap.removeEventProperty("chat_popup_is_visible");
  }
}, [chatPopupVisible]);

clearEventProperties()

Description
Removes all event-wide properties that were previously added with addEventProperties.

Examples
In this example, the app has a method checkoutComplete which is called when the finishes a purchase.

import { Heap } from '@heap/heap-react-native-bridge';

const checkoutComplete = () => {
  ...
  Heap.clearEventProperties();
};
- (void)checkoutComplete
{
  ...
  [Heap.sharedInstance clearEventProperties];
}

getEnvironmentId(): Promise<string | null>

Description
Returns a promise that resolves the current environment ID if Heap is recording, otherwise null.

Return Value
The current environment ID used for tracking events, or null if Heap is not recording.

Examples

import { Heap } from '@heap/heap-react-native-bridge';

const heapUserId = await Heap.getUserId();

getUserId(): Promise<string | null>

Description
Returns a promise that resolves to the current user ID if Heap is recording, otherwise null.

Return Value
The current Heap-generated user ID used for tracking events, or null if Heap is not recording.

Examples

import { Heap } from '@heap/heap-react-native-bridge';

const heapUserId = await Heap.getUserId();

getIdentity(): Promise<string | null>

Description
Returns a promise that resolves to the identity if Heap is recording and the user has been identified, otherwise null.

Return Value
The value that was provided to identify for the current user, or null if Heap is not recording or identify has not been called.

Examples

import { Heap } from '@heap/heap-react-native-bridge';

const heapIdentity = await Heap.getIdentity();

getSessionId(): Promise<string | null>

Description
Returns a promise that resolves to the current session ID if Heap is recording and the session has not expired, otherwise null.

This method is useful for reading the current state for purposes such as logging. If you are using the session ID for server-side events, it's recommended that you use fetchSessionId(), which will create a new session if needed.

Return Value
The current Heap-generated session ID, or null if Heap is not recording.

Examples

import { Heap } from '@heap/heap-react-native-bridge';

const heapSessionId = await Heap.getSessionId();

fetchSessionId(): Promise<string | null>

Description
Returns a promise resolving to the current session ID if Heap is recording, otherwise null.

If the previous session has expired, this will start a new session.

Return Value
The current Heap-generated session ID, or null if Heap is not recording.

Examples

import { Heap } from '@heap/heap-react-native-bridge';

const heapSessionId = await Heap.getSessionId();

Heap React Native Autocapture Reference

Requirements + Known Limitations

  • Pageview autocapture requires React Navigation 5.0 and later or React Native Navigation 7.0 and later.
  • Heap depends on BabelJS to instrument common views. Custom elements that don't use these building blocks will not be automatically captured.

API Reference

Babel instrumentation

Before building your app, you'll need to add the @heap/heap-react-native-autocapture plugin to your BabelJS configuration:

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: ['@heap/heap-react-native-autocapture'],
};
{
  "presets": [
    "module:metro-react-native-babel-preset"
  ],
  "plugins": [
    "@heap/heap-react-native-autocapture"
  ]
}

Note: If not using a React or React Native BabelJS preset, you'll also need to include @babel/plugin-transform-react-display-name in your BabelJS configuration to make sure event hierarchies are properly captured.

Registration

When @heap/heap-react-native-autocapture is added to an app, it doesn't automatically start instrumenting the app or capturing events. For touch events and pageviews to be captured, you first need to register the source and start recording. This is done using registerHeapAutocapture.

registerHeapAutocapture(isDefault?: boolean)

Description
Registers the Heap React Native Autocapture SDK. Once registered, the SDK will autocapture UI interactions and source pageviews.

Parameters

  • isDefault (optional): Indicates whether or not the Heap React Native Autocapture SDK should be the default source. This setting informs the Heap React Native Bridge SDK to use the Heap React Native Autocapture SDK as a fallback for assigning pageview information to events if those events do not have a currently registered source or if their source fails to return a valid pageview. Defaults to false.

Examples

import { Heap } from '@heap/heap-react-native-bridge';
import { registerHeapAutocapture } from '@heap/heap-react-native-autocapture';

Heap.startRecording('YOUR_APP_ID');
registerHeapAutocapture(true);

Suppressing Sensitive Data

By default, Heap attempts to capture most non-input text from an interaction, including things like button labels, accessibility properties, and the full hierarchy from the touched view. Depending on how your app is designed, some sensitive information may be exposed to events:

  • Pageview titles or on-screen labels may contain usernames or email addresses.
  • Custom inputs like a pin input or calendar can receive individual touches.

In apps with a higher amounts of sensitive data or more restrictive requirements, there are global settings available through autocapture configuration options in startRecording. For apps with certain views or controls that need to be restricted, <HeapIgnore> can be used to suppress events and event properties.

For example, an app may have the following component:

const PinView = (props) => {
  return (
    <View>
      <Button title="1" rounded />
      <Button title="2" rounded />
      ...
    </View>
  );
};

By default, tapping buttons will produce events with the hierarchy PinView Button[title=1][rounded=true] and target text of "1".

There are several ways to filter different aspects of the view.

<HeapIgnore>

Wrapping a view with <HeapIgnore> will suppress all events inside the view. For example:

import { HeapIgnore } from '@heap/heap-react-native-autocapture';

<HeapIgnore>
  <PinView />
</HeapIgnore>

Tapping the buttons in this view will not produce events.

There are 5 props that can be used to expose partial information.

  • allowInteraction - This allows events to be captured with the remaining props determining how much is exposed. Without any other options, the bottom of the hierarchy is the view immediately inside <HeapIgnore>. In the same event from above, the hierarchy would be PinView.
  • allowInnerHierarchy - This allows the full hierarchy to be exposed, but without properties or text capture. In the same event, you would have a hierarchy of PinView Button.
  • allowProps - This allows property capture, but will exclude text-containing properties if the below options are omitted. In the same event, you would have a hierarchy of PinView Button[rounded=true].
  • allowText - This allows text capture. It can be used alongside allowProps to expose text-containing properties.
  • allowAccessibilityLabel - This allows accessibilityLabel capture.

<HeapIgnoreText>

Wrapping a view with <HeapIgnoreText> will capture events but exclude text and accessibility labels from the event. For example:

import { HeapIgnoreText } from '@heap/heap-react-native-autocapture';

<HeapIgnoreText>
  <PinView />
</HeapIgnoreText>

Tapping the buttons in this view will produce events, but with a hierarchy PinView Button[rounded=true] and no target text. This is equivalent to <HeapIgnore allowInteractions allowInnerHierarchy allowProps>.

withHeapIgnore

withHeapIgnore takes a component and returns a Higher Order Component that wraps it. This component accepts the same arguments but has <HeapIgnore> already applied.

In the below example, PinView is implemented with RedactedButton, a control that wraps Button. It accepts all the same arguments but has the ignore rules built in.

import { withHeapIgnore } from '@heap/heap-react-native-autocapture';

const RedactedButton = withHeapIgnore(Button, { allowInteraction: true });

const PinView = (props) => {
  return (
    <View>
      <RedactedButton title="1" rounded />
      <RedactedButton title="2" rounded />
      ...
    </View>
  );
};

Performance Impact FAQ

Performance

What is the performance impact of Heap on a Mobile app?

Heap adds virtually zero performance overhead. Heap never blocks the UI thread of the application, and memory is only allocated to process events right before they’re persisted or sent to the server.

Does Heap do a ton of main thread writes that could impact the responsiveness of the application?

Heap does not perform any data persistence or networking activity on the main thread. All data persistence and networking operations take place on a background thread.

Heap does perform a very small amount of view traversal on the UI thread to fetch event properties from the corresponding UI objects. This operation is very fast, and only involves simple property access. All data that's gathered on the UI thread is sent to a background thread for processing.

Network

Are events stored if there is no internet connection or are they dropped? How many events get stored?

All event data is stored in an SQLite database in application private storage. While online, this database should never grow to more than a few dozen events. While offline, all events are stored in the database until they’re able to be uploaded to the server. However, all data more than 6 days old will be routinely pruned from the database to prevent the database from growing endlessly.

Does this behavior differ between core and autocapture SDKs?

No. Autocapture data is sent to Core for storage.

How does Heap's event tracking impact network bandwidth?

Heap sends event data in small batches every 15 seconds while connected to the internet. While offline, network data remains in storage and no uploads are attempted.

What about network data consumption?

Events are roughly 0.5KB in size. Even if we estimate that a typical user produces 2,000 events per day, this only amounts to a single megabyte of data consumption.

How does Heap mitigate impacting bandwidth?

Heap batches event data to be sent to the server every 15 seconds to prevent constant network access. Heap also only sends a maximum of 100 events at a time, amounting to roughly 100KB of data per upload. Additionally, if any network errors occur, Heap pushes back the upload process for a full minute to wait for network conditions to improve.

Device

Is the user battery life impacted because Heap is running?

Heap should not impact battery life in any meaningful way. Events are batched to be sent periodically to prevent constant network access. This upload frequency should closely match the frequency of network activity of regular app usage for connected applications. If the target application doesn’t not routinely access the network, Heap’s upload interval can be increased to reduce network access and mitigate any unnecessary battery usage.