Integrating Mixpanel into a React and Redux application

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:


npm install --save mixpanel-browser

Import the mixpanel-browser 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:

import mixpanel from 'mixpanel-browser'

// ... inside component
componentDidMount () {


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:

export const loginUser = (data) => {
  /* Log in user via ajax...
   * With success 'json'...
  const { user } = json
  mixpanel.people.set({ '$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:
  // Pulling the 'user' object from the user store
  const user = action.payload.user.user
  mixpanel.people.set({ '$email': })

  return state

Tracking events

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

export const 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 a little strange 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.

One Reply to “Integrating Mixpanel into a React and Redux application”

Leave a Reply

Your email address will not be published. Required fields are marked *