DEV Community

loading...

Mixpanel in React Native with Context API

alejandrogutierrezb profile image Alejandro Gutierrez ・2 min read

I recently came across Mixpanel, as a nice analytics service to quickly implement in your projects regardless the stack you use.

However, their RN example is using classes and I felt like their app example was also a bit confusing and not quite DRY, so I implemented using the more modern ContextAPI and Functional Components. And I felt like this was worth sharing with the community and even the mixpanel team so they can add it to their docs.

1. Lets create the Consumer and Provider

import React from 'react';
import {Mixpanel} from 'mixpanel-react-native';

export const MixpanelContext = React.createContext();

export const MixpanelProvider = ({children}) => {
  const [mixpanel, setMixpanel] = React.useState(null);

  React.useEffect(() => {
    const initMixpanel = async () => {
      const initializedMixpanel = await Mixpanel.init('your token');
      initializedMixpanel.serverURL = 'https://api-eu.mixpanel.com'; // if needed
      setMixpanel(initializedMixpanel);
    };

    initMixpanel();
  }, []);

  return <MixpanelContext.Provider value={mixpanel}>{children}</MixpanelContext.Provider>;
};
Enter fullscreen mode Exit fullscreen mode

2. Wrap your App Component

So that you can access the context globally.

import React from 'react';
import {MixpanelProvider} from 'path.../AnalyticsService';

const App = () => {
  return (
          <MixpanelProvider>
            {children}
          </MixpanelProvider>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

3. Consume your context in any Component

import React from 'react';
import {Text, TouchableOpacity, View} from 'react-native';
import {MixpanelContext} from 'path.../AnalyticsService';

//simple example to get the point, customize it however you want

export const SomeComponent = () => {
  const mixpanel = React.useContext(MixpanelContext);
  return (
    <View>
          <TouchableOpacity onPress={() => mixpanel.track('Testing mixpanel')}>
            <Text>Test mixpanel</Text>
          </TouchableOpacity>
        )}
    </View>
  );
};
Enter fullscreen mode Exit fullscreen mode

Hope it was helpful. I didn't went deep into the nits&grits as i felt like react docs are well explained and you can find many brilliant and free videos on the topic as well.

Nevertheless, let me know if you have any doubts.
You can also contact me at https://www.linkedin.com/in/alejandrogutierrezb/

Discussion (0)

pic
Editor guide