Integrating Mixpanel into a React and Redux application

Datetime:2016-08-23 00:11:18          Topic:          Share

I did some work recently on integrating Mixpanel into a project I’ve been building. Integrating Mixpanel was a lot easier than I thought, but there were a couple complicated bits in getting it to work as expected with a React / Redux application. Here are the steps:

Installation

npminstall --savemixpanel-browser

Import the mixpanel library and initialize it somewhere near the beginning of your app’s component lifecycle. I did this in my AppContainer (using the usual React component lifecycle methods), which renders out the router and components:

importmixpanelfrom 'mixpanel-browser'
 
// ... inside component
componentDidMount () {
  mixpanel.init('your_mixpanel_token')
}

Identification

Identify your user and pass any additional information (name and email, for instance). This can be a tricky one depending on how your application’s redux flow is structured–it would make the most sense to do it as part of an action, but depending on your app’s concerns (persistence being a primary issue for my app), it might need to also happen in the reducer. Here’s how it’d look in an action:

exportconst loginUser = (data) => {
  /* Log in user via ajax...
   * With success 'json'...
  */
  const { user } = json
  mixpanel.identify(user.id)
  mixpanel.people.set({ '$email': user.email })
}

In my application, the store is persisted into local storage using redux-persist , so in the reducer, separately handling an already-logged in user via the store rehydrating looks like:

import { REHYDRATE } from 'redux-persist/constants'
 
// in your reducer, handling the REHYDRATE type:
caseREHYDRATE:
  // Pulling the 'user' object from the user store
  const user = action.payload.user.user
  mixpanel.identify(user.id)
  mixpanel.people.set({ '$email': user.email })
 
  return state

Tracking events

With an identified user, you can begin tracking events in your actions:

exportconst doAThing = () => {
  mixpanel.track('Do a thing')
  return {
    type: DO_A_THING
  }
}

If you need to act on the tracking event finishing, you can wrap the mixpanel call in a Promise and chain it:

const trackEvent = (action, options) => {
  return new Promise((resolve, _) => {
    mixpanel.track(action, options, response => resolve(response))
  })
}
 
trackEvent('Do a thing').then(response => _doMoreThings(response))

Overall, I’m pretty happy with how the Mixpanel + React integration turned out. The user identification feels gross with redux-persist, but when doing the identification as part of the login and sign up actions, it feels more intuitive than it would be than firing it as part of a button click callback.