Skip to content
Product analytics

An introduction to Product analytics with React & Amplitude

Understanding how users interact with your product and create better experiences by tracking, visualizing & analyzing.

Grégoire Mielle
by Grégoire MielleLast updated on 7/1/2022
Table of content

There’s more than gut and feelings when it comes to understanding what you should build next for your users and what does work (or do not work) for them. Data, and more specifically product analytics, has become an essential tool for product teams for that matter.

Product analytics in a nutshell

It’s easy to come up with vanity metrics like monthly recurring revenue (MRR). However, it does not help you to understand how users interact with your product or create better experiences for them.

With Product analytics, you track, visualize & analyze in order to answer the following questions:

  • What’s the typical journey to start a booking flow?
  • How much time is spent at each step?
  • What are the most & least used features of a listing view?
  • What’s the conversion rate of the host onboarding?
  • Are most actives users using filters more than new users?

When is Product analytics valuable?

Gaining visibility into users actions is valuable at any stage of a company, especially when its product is a web app.

  • Creation stage: it’s all about finding a product-market fit, building the features that your users need. Data is scarce but helps you validate ideas, understand what’s working & what’s not.
  • Growth stage: it’s all about capturing as many customers as possible. A lot of features are implemented & the volume of usage data is growing rapidly. It helps you identify bottlenecks & scale things.
  • Scale stage: it’s all about establishing your product as a reference. Usage data is used to optimize critical paths, A/B test new solutions & keep getting insights on new features.

The steps of Product analytics

Product analytics consist of multiple steps. How much you get from it depends on your company’s experience & maturity at them:

  • Collect data: instrument your web app to receive events on how users navigate & what actions they perform.
  • Integrate data: aggregate & transform information across subdomains (billing, support, your product features) to get a 360 view of your users.
  • Analyze data: refute or validate an hypothesis based on your 360 view and build the next experiment/test you want to perform.
  • Empower everyone with data: make data the fuel of your iterative process by letting everyone ask questions, find answers & understand indicators of success.

How to integrate Amplitude with a React app?

💡

The code snippets used in this section are part of a demo application using React.js & Amplitude. A GitHub repository containing all the source code is available.

Why Amplitude?

There are a lot of Product analytics solutions around there: Mixpanel, Amplitude, Pendo and Fullstory to name a few.

Amplitude brings a lot to each of the steps described above in a single platform. From a technical standpoint, it’s easy to integrate across your stack (mobile, web, server-side). Moreover, it has a pricing model which adapts as you’re growing.

Let’s see how you can use it in your React app.

The set up

When using a Product analytics solution like Amplitude in a React app, you need to initialize a session when our app is first loaded for the current logged-in user. You can then push events to Amplitude associated to this user & session while they navigate the app.

This session takes the shape of a React context provider. You want this provider to be an abstraction on top of Amplitude. This way, you can easily plug additional analytics solutions (eg. Pendo, Fullstory, Mixpanel) for which you wish to push events. In the future, it might be even more interesting to rely on Segment to collect events & push them to different destinations.

import React from 'react'
import { AnalyticsProvider } from './analytics'

const Root = () => {
  /**
   * Use your own logic to populate
   * the user id & attributes
   */
  const { user } = useAuth()

  return (
    <AnalyticsProvider
      amplitudeApiKey="change-me"
      user={{
        id: user.id,
        attributes: {
          plan: user.company.plan,
          companyId: user.companyId,
        },
      }}
    >
      <App />
    </AnalyticsProvider>
  )
}

Once our React context is set up, you can start pushing events on user actions. Depending on your strategy (auto-tracking or manual-tracking), some or every user actions will be collected.

Here you’re gonna use a React hook to push events. This hook can be used in individual components or within a shared one (like a design system Actionable or Button component).

import { useAnalyticsPushEvent } from './analytics'

export const OnboardingButton = ({ onClick, currentStep, label }) => {
  const pushEvent = useAnalyticsPushEvent()

  return (
    <button
      onClick={() => {
        onClick()
        pushEvent('onboarding.navigation.buttonClicked', { currentStep })
      }}
    >
      {label}
    </button>
  )
}

When the number of tracked events increases, a good practice is to maintain a list of all of them. This way, you can rely on constants instead of strings to avoid typos.

/**
 * Event names can be grouped by sections
 * or team scopes. This way, it's easier
 * to review naming conventions & to have
 * proper governance (who owns what)
 */
export const analyticsEvents = {
  onboarding: {
    navigationButtonClicked: 'onboarding.navigation.buttonClicked',
  },
}

Finally, you can track which screens or sections are viewed by users during sessions & how much time they spend on each of them. A simple approach to this requirement is a container/wrapper component in charge of pushing these events.

import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { AnalyticsView } from './analytics'

const Router = () => {
  ;<BrowserRouter>
    <Routes>
      <Route path="/" element={<App />}>
        <Route
          index
          element={
            <AnalyticsView name="home">
              <Home />
            </AnalyticsView>
          }
        />
        <Route
          path="listings"
          element={
            <AnalyticsView name="listings" attributes={{ version: 2 }}>
              <Listings />
            </AnalyticsView>
          }
        />
      </Route>
    </Routes>
  </BrowserRouter>
}

Each time a user visits a route, an event is pushed when they display it and when they leave it to know how much time they spent on it.

Now that you know how to instrument your React app by pushing events on user actions & visits, let’s see what are the essential elements to track.

What to track in terms of product usage in our React app?

There are a lot of analyses that you can do from your events like journey analysis, funnel conversion or cohorts comparisons (see this terms list from Amplitude to learn more about vocabulary).

While you might not be in charge of creating dashboards to visualize these things, the right events need to be collected from your app. Let’s see what events you can start with to better understand how users interact with your product.

It’s essential to track page views & navigation events (eg. Sub menu item clicked, main page CTA clicked to start a flow, “Go back” button clicked) to understand how users navigate your app.

This way, you can build journey analyses to discover how users land to your features, where they’re lost or spend the most time.

It can be achieved by tracking individual clicks on navigation items & wrapping your routes with an AnalyticsView . A more automatic way of tracking these actions would be to listen for location changes & called made to your navigation library (eg. React router push, goBack functions).

Flows & funnels

Critical paths in your app may be made of multiple steps that need to be completed by users. Tracking the progression through these steps is important to know where users are stuck or spend the most time.

Examples of these flows & funnels are onboarding flows, payment checkouts or creation forms. Each step can be wrapped into an AnalyticsView and important actions within steps can be tracked with individual events (eg. help tooltip hovered).

Individual actions

Finally, individual actions on new features or critical pages can be tracked. They can help understand what are the most/least used features or zones of a screen, what variation of a component is performing better, etc.

5 tips for effective product analytics

Make data a priority & lever of action for everyone

Product analytics should empower all product team members to make better decisions. It takes a lot of collaboration between engineers, designers & product managers to make collecting, integrating & analyzing data valuable for everyone.

Integrate Product analytics into your iterative process

Every product development decision should be backed by data, from discovering opportunities to analyzing feature launch outcomes.

Reference users & entities in a uniform way across departments

Do we aggregate events by collaborator id or individual id? How do I link a subscription to a company if I only have a customer id and not a company id? While every team has its own language, building a 360 analytics view requires to aggregate data across them.

You need to identify which unique identifiers can be used to perform this task and avoid unnecessary transformation work or worse, a partial view of what’s happening.

Use tools like Segment to push once, deliver multiple times

As your Product analytics stack grows, you might want to use complementary tools which also need to receive events from your app. Using tools like Segment, you only need one script to load & push events from within your app.

Segment is in charge of transforming and publishing these events to multiple destinations.

Use feature flagging & A/B testing to go further

With feature flagging, you can release features to users progressively. With A/B testing, you release different versions of a feature to different users.

Once you start tracking user actions within your app, it is easier to experiment different solutions to a common problem & compare how they perform.

Want to ship localized content faster
without loosing developers time?

Recontent helps product teams collaborate on content for web & mobile apps.
No more hardcoded keys, outdated text or misleading translations.