Monitoring & Analytics
Implement comprehensive monitoring, analytics, and error tracking for production React applications. This is a foundational concept in component-based UI development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world React experience. Take your time with each section and practice the examples
Error Tracking
Set up error tracking and monitoring to catch and analyze errors in production applications.. This is an essential concept that every React developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Sentry Integration
// Sentry setup
import * as Sentry from '@sentry/react';
import { BrowserTracing } from '@sentry/tracing';
Sentry.init({
dsn: process.env.REACT_APP_SENTRY_DSN,
integrations: [
new BrowserTracing(),
],
tracesSampleRate: 1.0,
environment: process.env.NODE_ENV,
});
// Error boundary with Sentry
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
Sentry.captureException(error, {
contexts: {
react: {
componentStack: errorInfo.componentStack
}
}
});
}
render() {
if (this.state.hasError) {
return <div>Something went wrong.</div>;
}
return this.props.children;
}
}Performance Monitoring
// Performance monitoring
import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';
const sendToAnalytics = (metric) => {
// Send to your analytics service
gtag('event', metric.name, {
value: Math.round(metric.value),
event_label: metric.id,
non_interaction: true,
});
};
// Measure Core Web Vitals
getCLS(sendToAnalytics);
getFID(sendToAnalytics);
getFCP(sendToAnalytics);
getLCP(sendToAnalytics);
getTTFB(sendToAnalytics);User Analytics
// Google Analytics 4 setup
import ReactGA from 'react-ga4';
const GA_TRACKING_ID = process.env.REACT_APP_GA_TRACKING_ID;
ReactGA.initialize(GA_TRACKING_ID);
// Track page views
const trackPageView = (path) => {
ReactGA.send({ hitType: 'pageview', page: path });
};
// Track custom events
const trackEvent = (action, category, label, value) => {
ReactGA.event({
action,
category,
label,
value
});
};
// Usage in components
useEffect(() => {
trackPageView(window.location.pathname);
}, []);Health Checks
// Health check endpoint
const healthCheck = {
status: 'healthy',
timestamp: new Date().toISOString(),
version: process.env.REACT_APP_VERSION,
environment: process.env.NODE_ENV,
uptime: process.uptime(),
memory: process.memoryUsage()
};
// API health monitoring
const checkAPIHealth = async () => {
try {
const response = await fetch('/api/health');
const data = await response.json();
return data.status === 'healthy';
} catch (error) {
console.error('API health check failed:', error);
return false;
}
};Mini-Project: Complete Monitoring System
// Complete monitoring and analytics system
import React, { useEffect } from 'react';
import * as Sentry from '@sentry/react';
import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';
// Performance monitoring
const initPerformanceMonitoring = () => {
const sendToAnalytics = (metric) => {
// Send to your analytics service
if (window.gtag) {
window.gtag('event', metric.name, {
value: Math.round(metric.value),
event_label: metric.id,
non_interaction: true,
});
}
};
getCLS(sendToAnalytics);
getFID(sendToAnalytics);
getFCP(sendToAnalytics);
getLCP(sendToAnalytics);
getTTFB(sendToAnalytics);
};
// Error tracking
const initErrorTracking = () => {
Sentry.init({
dsn: process.env.REACT_APP_SENTRY_DSN,
environment: process.env.NODE_ENV,
beforeSend(event) {
// Filter out development errors
if (process.env.NODE_ENV === 'development') {
return null;
}
return event;
}
});
};
// Analytics tracking
const initAnalytics = () => {
if (process.env.REACT_APP_GA_TRACKING_ID) {
// Initialize Google Analytics
window.gtag('config', process.env.REACT_APP_GA_TRACKING_ID, {
page_title: document.title,
page_location: window.location.href
});
}
};
// Custom hook for monitoring
const useMonitoring = () => {
useEffect(() => {
initPerformanceMonitoring();
initErrorTracking();
initAnalytics();
}, []);
const trackEvent = (action, category, label, value) => {
if (window.gtag) {
window.gtag('event', action, {
event_category: category,
event_label: label,
value: value
});
}
};
const trackError = (error, context = {}) => {
Sentry.captureException(error, {
extra: context
});
};
return { trackEvent, trackError };
};
export default useMonitoring;