Suraj Vishwakarma I am an enthusiastic programmer who loves to write code and blog posts so that others can understand technology.

react-tracking: Declarative tracking for React apps

3 min read 1083

React Declarative Tracking

Tracking a user on your webpage has numerous benefits. For example, tracking provides insights into how a user interacts with your webpage, indicating which components of your UI are the most and least often used.

Declarative tracking is a method of tracking the interactions of a user on a webpage. Traditionally, we use the DOM to track all user interactions, however, the evolution of the component-based framework has enabled us to use component-based tracking in our applications.

One library for declarative tracking in React is react-tracking, which implements tracking for each component of the page. You can use Hooks and decorators to declare tracking on events like click events, states, functional components, class components, and more. Additionally, you can compartmentalize tracking concerns to individual components, avoiding leaking across the entire app.

In this article, we’ll look into declarative tracking using the react-tracking library. To follow along with this article, you should be familiar with React and React Hooks. Let’s get started!

How does react-tracking work?

We can break down react-tracking into three main components. For one, trigger kickstarts the tracking process and can be a click event, loading event, etc. Essentially, trigger is the interaction of the user with the element in the application.

component is the component that we are tracking. Usually, component refers to forms, cards, etc. You can track functional as well as class-based components. All tracking data will be wrapped inside the dispatch component and will be displayed in the console when triggered. If you don’t define the dispatch component, the tracking data will be pushed to window.dataLayer[], which is ideal for Google Analytics.

With these three components, we can use react-tracking to track any component in our application. Let’s see it in action by running through an example.

react-tracking example: Tracking on click button

As an example, we’ll use a click button that tracks a functional component as well as a class component.

First, let’s set up up the environment required to get started with react-tracking. We’ll use VS Code as our code editor, which is powerful and includes extensions to help you write better code. If you’re familiar with a different code editor, feel free to use that instead.

Setting up React

To install react-tracking, we first need to install React. We’ll create a small program that will track the button click event in a functional and class component. The class button will also track the number of clicks.

First, we’ll install React as follows:

npm init react-app my-app

With React installed, we can install the react-tracking library. Run the command below:

npm install --save react-tracking

With React and react-tracking installed, we’ll go ahead and get started with our code.



react-tracking imports

We’ll need to import the following elements from react-tracking:

  • React
  • useTracking: Used as a Hook to track any event
  • track: Used to track class and member functions with the @ decorator and dispatch all the tracking data to the console

Import the items above with the command below:

import track, { useTracking } from "react-tracking";
import React from "react";

Functional component

The functional component will contain the useTracking() Hook, which is used to track the clickbutton event. useTracking() then dispatches button click data to the console.

Below, we have an onClick event function for the button that contains trackEvent. Here, you can pass the message that you want to display in the console, which we’ll add later:

const HookButton = () => {
  const {trackEvent} = useTracking()
  return (
    <div>
      <h2>Click for HookButton</h2>
      <button onClick={()=> trackEvent({funComponent:'HookButton', event: "HookButton-Clicked"})}>Click Me!</button>
    </div>
  );
}

class component

In the class component, we’ll track the button click event along with the number of clicks. To track the class component, we’ll use track, followed by the message we’ll set.

In class, we have a state to count the number of clicks. In return, we’ve rendered a button with the click event linked to the handleClick function.

We’ve also tracked the member function of the class with track. We have an arrow function with the state as props to pass the value of numClicked. In the handleClick function, we have increased the state value of numClicked by 1 each time the button is clicked:

@track({class:'ClassButton'})
class ClassButton extends React.Component{
  state = {
    numClicked : 1
  };

  @track((props, state) =>({event:'ClassButton-Clicked', clickCount:state.numClicked}))
  handleClick = () => {
    this.setState({
      numClicked: this.state.numClicked + 1
    })
  }
  render(){
    return(
      <div>
        <h2>Click for ClassButton</h2>
        <button onClick={this.handleClick}>Click Me!</button>
      </div>
    )
  }
}

App component

Now, we’ll wrap the HookButton functional component and the ClassButton class component in the App component:

const App = () =>{
  return(
    <div className="App">
      <h1>React-Tracking</h1>
      <HookButton />
      <ClassButton />
    </div>
  )
}

dispatch component

The dispatch component is a functional component that will render in the console when triggered. You can add your own message to dispatch like Component: "Apps". dispatch uses track to display the content that we define inside it in the console.

We’ll also use dispatch to dispatch all the data we collected into the console, followed by the component that you want to render on the page. Next, we just need to export the functional component that contains the track logs:

const TrackedApp = track(
  { Component: "Apps" },
  {
    dispatch: data => {
      console.log(data);
    }
  }
)(App);

export default TrackedApp

The output of the code above is as follows:

React Tracking Hook Button Class Button Output

You can find tracking details in the console when you click the button.

HookButton click output:

{app: "my-app", funComponent: "HookButton", event: "HookButton-Clicked"}

ClassButton click output:

{app: "my-app", class: "ClassButton", event: "ClassButton-Clicked", clickCount: 1}

clickCount will increase as you continue clicking the button. You can find the code and experiment with it in the CodeSandbox:

Conclusion

In this tutorial, we explored react-tracking, which does a pretty good job of tracking all events and providing important details in the console. We created a program to track the click button event and show the tracking data on each click. The @ decorator, along with track, can track most of the data in React, including data in props and state.

You can use the steps in this tutorial to track different components and classes in your application. I hope you’ll consider react-tracking in your next project. Thanks for reading, and be sure to leave a comment if you have any questions.

Cut through the noise of traditional React error reporting with LogRocket

LogRocket is a React analytics solution that shields you from the hundreds of false-positive errors alerts to just a few truly important items. LogRocket tells you the most impactful bugs and UX issues actually impacting users in your React applications. LogRocket automatically aggregates client side errors, React error boundaries, Redux state, slow component load times, JS exceptions, frontend performance metrics, and user interactions. Then LogRocket uses machine learning to notify you of the most impactful problems affecting the most users and provides the context you need to fix it.

Focus on the React bugs that matter — .

Suraj Vishwakarma I am an enthusiastic programmer who loves to write code and blog posts so that others can understand technology.

Leave a Reply