React Native in Real Time: Pub/Sub, Geolocation, Presence

pubnub share

As our collective attention spans continue to decrease, interactivity needs to grow. Waiting for servers to spin up or images to load delays a real-time user experience. In such a media-consuming society, waiting for a website to load feels unacceptable; “I have 4G right now, what’s taking so long?”

In this article, I will share with you what I believe the future of applications will be. I want to show off how simple bringing apps to modern standards of speed and security is. This is important for those of you deciding what kind of language, framework, or networking technology to create projects with. Real-time is going to be the only speed that matters soon, and anything slower will be left in the dust. 

This demand for our browsers and apps to function in real time has changed the technology ecosystem. Each new technological advance gets us to where we want to go, faster. To the average person, this means knowing where your Uber driver is. For developers, it means connecting all the devices on Earth into faster and smoother connected experiences.

React Native Real Time Trends 

Digital customers want information right now. We are long past the days of the Pony Express delivering messages halfway across the country in ten days. If you’re not providing users an instantaneous experience, they’ll try to find it somewhere else. 

As new connection speeds become available around the world, there are more people participating in this real-time, interactive world than ever before. In addition to ridesharing and food-delivery services growing inside the US, there is booming growth for those same industries in south-east Asia and India. Swiggy and Zomato, food delivery services popular in India, complete over 500,000 deliveries a day. Both of those companies depend on real-time, and so do their customers. It is becoming much more than an experimental group of startups providing these services; it’s becoming a part of everyday life around the world. 

With new developments such as 5G, our software data transfer speeds need to improve, to avoid bottlenecking. Web and mobile applications now have the power to update in real time, bringing users closer together. One of the ways to connect experiences better together is by using React Native.  With React Native your application can respond to real-time events and satisfy the ever-growing, technology-reliant world. 

What is React Native for Real Time?

To fit this need for speed, the developers at Facebook created a JavaScript framework called React. React allows for fast and lightweight web pages to be built using only JavaScript and JavaScript syntax extension (JSX). JSX is a way of designing user interfaces in an XML like format, yet keeping all the power of JavaScript. React also lets small parts of these sites update versus entire pages needing to reload for any changes.  This speeds up websites and makes them feel much cleaner with these smooth updates.

After creating React, which is designed for web pages, they extended its component structure to React Native. It allows us to create mobile applications using some of the same ideas as React. It takes the JavaScript that we write and runs it on the mobile device. Then it connects each component through a bridge to a native iOS or Android component. Bridges allow the JavaScript we have running to push information to those native components.

Bridges diagram

React Native utilizes a component structure, and components can contain other components. If some information related to a specific component changes, then only that one will re-render. By only re-rendering when needed, this structure makes apps and webpages fast, smooth, and efficient. Due to this system inside of React and React Native, they’re a great option for creating

React Native is a perfect base for a real-time app, but it does not provide the connection services we need. PubNub fills this role of providing users with an uninterrupted and secure connected experience.

Why Should I Use PubNub as a Real-time Service?

Starting with React Native as our base app, we need to connect our devices or users in some way. PubNub is a great fit for this role, especially since it not only connects users, it does it fast. With Points of Presence around the world, PubNub can serve the world in an instant. When combining React Native with it, we connect users in a common shared experience.

PubNub is one of the leading

Networks, with Pub/Sub and many other features available. PubNub is FREE up to 1,000,000 messages a month. In addition to a huge free tier, it’s easy to use. It’s a simple process to drag and drop some starter code into your project, get connected, and start pub/sub messaging.

Stop setting up servers and worrying about many connections to different

. PubNub handles your backend, letting your clients know the information that’s important to them. It provides a Pub/Sub infrastructure and lets you build on top of it. Send whatever data you want, and PubNub will make sure it gets to each user. In our case, we will be using PubNub's pub-sub, history,
, and presence.

Below, we’ll go over the startup process and a few code snippets that are useful in common React Native use cases.

Real-time React Native Basics

Let’s go over some features of PubNub which will allow you to build common features for real-time apps. There’ll be code snippets and links to more information in each example.

Connecting PubNub to React Native

Type the following code into your terminal to install PubNub into your React Native project. This also installs the dependencies natively.

npm install --save pubnub pubnub-react
react-native link pubnub-react

The following is an example of how a general React Native App would look with everything needed to start using PubNub. 

import PubNubReact from 'pubnub-react';

export default class App extends Component {
  constructor(props) {
    this.pubnub = new PubNubReact({
      publishKey: "INSERT PUBLISH KEY HERE",
      subscribeKey: "INSERT SUBSCRIBE KEY HERE"

    //... Rest of the constructor including state object


  //... Rest of your App component


First, we import PubNub at the top of the file. Inside of our component’s constructor, we create the PubNub object and insert our keys. After creating our state object, we can use the init function in our PubNub object. For a more detailed explanation on setting up PubNub with React Native, check out the PubNub React SDK Documentation.

Publishing and Subscribing 

Pub/Sub Messaging is PubNub’s bread and butter. Most use cases require some version of Pub/Sub to make an app real-time. Pub/Sub is as easy as a single call. You can include an object or a string into the publish and then anyone subscribed to the channel will receive it in a tenth of a second or less. That’s it, one call to subscribe, and one to publish. You can even create a message handler that lets you process the message being received.

  channels: ["channel1"],
  withPresence: true

this.pubnub.getMessage("channel1", msg => {
  console.log( + " loves " + msg.message.awesomeRDSN)

  message: {
    name: "Samba",
    awesomeRDSN: "PubNub"
  channel: "channel1"


A great use case for Pub/Sub is messaging! Either one to one, many to many, or anywhere in between, PubNub can handle it. We’ve got a great, growing tutorial series on creating a chat app in React Native.

Storage & Playback

Storing and retrieving messages is an important part of any messaging app, and that’s where Storage & Playback comes into play. Below is a sample history call you can reference.

    channel: 'channel1',
    count: 100, // 100 is the default
  (status, response) => {

In this snippet, we call the history function on our PubNub object and insert our arguments. We then go into a callback that allows us to access the response from our call. You can then display, parse, or do whatever you want to these messages.

For more information and options on this function, check out the Storage & Playback documentation.


Whether your use case includes streaming live location updates or

proximity notifications, they’ve never been easier with PubNub. Using react-native-maps, you can use the MapView component and its children to navigate around the world. You may place the markers provided or create custom ones to represent your use case.

import MapView, {Marker} from 'react-native-maps';

//Insert this into your componentDidMount or 
//other functions to track and publish users positions. 
//Part of the React Native Geolocation API - no need to import
  position => {
        message: {
          uuid: this.pubnub.getUUID(),
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
        channel: "global"
  error => console.log("Maps Error: ", error),
    enableHighAccuracy: false,
    distanceFilter: 100

//Components in the render function from react-native-maps
 { => (

Here is an example snippet of a MapView with a Marker inside of it. Every time the device moves a preset distance, you can set some functionality, like publishing the coordinates of the device.  It also publishes the location every time the device moves a set distance. Check out a full tutorial on creating a geo-tracking app using React Native.

Mobile Push Notifications

PubNub has the ability to send Mobile Push Notifications as well. These allow you programmatically make sure your customers know what is happening, even when your app is not in the foreground. With both APNS and FCM, you can keep iOS and Android users in the know, even when they’re off of your app. Find out how to use Mobile Push Notifications in your React Native app.


Presence is another important feature of PubNub that has a use in React Native. You can request a count of how many users are subscribed to a channel using the HereNow method. In addition to the occupancy, you can also receive each subscriber’s unique identifier. This allows you to tell who is in which channel and who is online. Check out the example below or the HereNow documentation.

    channels: ["channel1"],
    channelGroups: ["channel1"],
    includeUUIDs: true,
    includeState: true
  (status, response) => {

PubNub Presence also has another feature called state. We can set and get user information into their state object. This is useful for receiving information that users might not be publishing, and when one user comes online, they can request user states to populate their online indicators, like in a chat application. If you include Presence in your subscribe call, you’ll also be notified with state changes. Setting a user state has a multitude of use cases, check out the example below or visit the User State documentation.

    state: {
      "full_name": "James Patrick Page"
    uuid: "jbonham",
    channels: ['channel1']
  function(status) {
    // handle state setting status

    uuid: "jbonham",
    channels: ['channel1']
  function(status, response) {
    // handle state getting response


Functions allows serverless event handlers of JS code to run on PubNub messages in-transit. It can run either before or after the message gets delivered to its original sender. You can also create a REST API endpoint. The uses of this are too many to list, but PubNub has a whole catalog of open-source Functions. They contain potential uses and integrations with other APIs that are already defined for your use. These prewritten functions, called Blocks, handle everything from text translation to machine learning models. blocks gif

An example use of Functions in a React Native app is profanity filtering integrated into in-app chat. Use the Chat Message Profanity Filter Block or create your own function. Now make sure your function executes Before Publish or Fire so the data augmentation will happen in-transit.

Final Thoughts

Real-time is fueling the real-time revolution. React Native plays a role in this ecosystem by keeping the software side responsive to updates. PubNub powers the transfer of information between clients, with near-instant speed. Companies are ditching the server-client model, and instead moving to a more scalable and cheaper IaaS, like PubNub. Especially at 1,000,000 free messages a month, it’s easy to try out to see if it fits your use case.