Analytics
/

React hooks for analytics

Integrating analytics into your react apps with use-analytics


React hooks for analytics. This library adds some convenience methods when working with React & makes it a little easier to passing around the analytics instance while instrumenting your application.

Note: When using analytics with React, this library, use-analytics, hooks library is not required. See details below for using analytics with react without hooks.

Installation

Install analytics, use-analytics from npm.

npm install use-analytics analytics

How to use

After installing the analytics and use-analytics, include in your project.

Initialize analytics with your third-party plugins or custom plugins and pass it to the <AnalyticsProvider> component in the instance prop.

Wrapping your application with <AnalyticsProvider> is required for using use-analytics hooks.

import React from 'react'
import ReactDOM from 'react-dom'
import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics'
import { AnalyticsProvider, useAnalytics } from 'use-analytics'

/* Initialize analytics & load plugins */
const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    googleAnalytics({
      trackingId: 'UA-1234567',
    })
  ]
})

const Example = (props) => {
  const { track, page, identify } = useAnalytics()
  return (
    <div>
      <button onClick={() => track('trackThing')}>
        Track event
      </button>
      <button onClick={() => page()}>
        Trigger page view
      </button>
      <button onClick={() => identify('userID', { email: 'bob@bob.com' })}>
        Trigger identify visitor
      </button>
    </div>
  )
}

ReactDOM.render((
  <AnalyticsProvider instance={analytics}>
    <Example />
  </AnalyticsProvider>
), document.getElementById('root'))

For more information on how to use, checkout this example repo.

Demo video

useAnalytics hook

After the AnalyticsProvider is added to your application you can use the useAnalytics hook anywhere down the component tree.

import React from 'react'
import { useAnalytics } from 'use-analytics'

const Example = (props) => {
  const { track, page, identify } = useAnalytics()
  return (
    <div>
      <button onClick={() => track('trackThing')}>
        Track event
      </button>
      <button onClick={() => page()}>
        Trigger page view
      </button>
      <button onClick={() => identify('userID', { email: 'bob@bob.com' })}>
        Trigger identify visitor
      </button>
    </div>
  )
}

AnalyticsConsumer

Below is an example of using render props and the AnalyticsConsumer functional component and the render props pattern.

import React from 'react'
import ReactDOM from 'react-dom'
import Analytics from 'analytics'
import { AnalyticsProvider, AnalyticsConsumer } from 'use-analytics'

/* Initialize analytics & load plugins */
const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    googleAnalytics({
      trackingId: 'UA-1234567',
    })
  ]
})

ReactDOM.render((
  <AnalyticsProvider instance={analytics}>
    <AnalyticsConsumer>
      {(props) => {
        /* props contains the analytics API. https://getanalytics.io/api/*/
        const { track, page, identify, user } = props
        return (
          <div>
            <button onClick={() => track('trackThing')}>
              Track event
            </button>
            <button onClick={() => page()}>
              Trigger page view
            </button>
            <button onClick={() => identify('userID', { email: 'bob@bob.com' })}>
              Trigger identify visitor
            </button>
          </div>
        )
      }}
    </AnalyticsConsumer>
  </AnalyticsProvider>
), document.getElementById('root'))

withAnalytics

It's also possible to use withAnalytics higher order component to wrap components inside the <AnalyticsProvider /> component.

This will inject the analytics instance into this.props.analytics

Below is an example of using withAnalytics

import React, { Component } from 'react'
import { withAnalytics } from 'use-analytics'

class App extends Component {
  render() {
    /* props.analytics contains the analytics API https://getanalytics.io/api/*/
    const { analytics } = this.props
    const { track, page, identify } = analytics
    return (
      <div className="App">
        <div>
          <button onClick={() => track('trackThing')}>
            Track event
          </button>
          <button onClick={() => page()}>
            Trigger page view
          </button>
          <button onClick={() => identify('userID', { email: 'bob@bob.com' })}>
            Trigger identify visitor
          </button>
        </div>
      </div>
    )
  }
}

export default withAnalytics(App)

AnalyticsContext

If you are using React class components, you can leverage the static contextType field and set the AnalyticsContext.

import React from 'react'
import ReactDOM from 'react-dom'
import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics'
import { AnalyticsProvider, AnalyticsContext } from 'use-analytics'

/* Initialize analytics & load plugins */
const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    googleAnalytics({
      trackingId: 'UA-1234567',
    })
  ]
})

/* Example of class component using contextType */
class ComponentWithContextType extends React.Component {
  static contextType = AnalyticsContext
  render = () => {
    /* this.context contains the analytics API https://getanalytics.io/api/*/
    const { track, page, identify } = this.context
    return (
      <div>
        <button onClick={() => track('trackThing')}>
          Track event
        </button>
        <button onClick={() => page()}>
          Trigger page view
        </button>
        <button onClick={() => identify('userID', { email: 'bob@bob.com' })}>
          Trigger identify visitor
        </button>
      </div>
    )
  }
}

ReactDOM.render((
  <AnalyticsProvider instance={analytics}>
    <ComponentWithContextType />
  </AnalyticsProvider>
), document.getElementById('root'))

Analytics without hooks

Analytics works as a standalone package & the analytics instance can be imported into directly into any component and used.

// index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './app'

ReactDOM.render(MyComponent, document.getElementById('root'))

Then include a file where analytics is initialize & export the instance. This will be the file you include wherever you want to instrument custom events.

// analytics.js
import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics'
/* Initialize analytics & load plugins */
const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    googleAnalytics({
      trackingId: 'UA-1234567',
    })
  ]
})

export default analytics

For example, app.js below is including the analytics instance and can call the methods directly.

// app.js
import React from 'react'
import analytics from './analytics'

const MyComponent = (
  <div>
    <button onClick={() => analytics.track('trackThing')}>
      Track event
    </button>
    <button onClick={() => analytics.page()}>
      Trigger page view
    </button>
    <button onClick={() => analytics.identify('userID')}>
      Trigger identify visitor
    </button>
  </div>
)

export default MyComponent