R

React Handbook

Clean • Professional

Monitoring & Logging in React: Error Tracking and Performance Insights

4 minute

React Monitoring & Logging

Error Logging • Performance Monitoring • Runtime Error Handling

In production, monitoring and logging are critical for keeping your React application reliable, fast, and user-friendly.

They help you detect bugs before users report them, analyze performance bottlenecks, and recover gracefully from unexpected crashes.

This topic covers the three major pillars of React monitoring:

  1. Error Logging – Capture and analyze errors using tools like Sentry or LogRocket
  2. Performance Monitoring – Track runtime speed and bottlenecks
  3. Handling Runtime Errors – Graceful fallbacks and error boundaries

1. Error Logging – Using Sentry & LogRocket

What is Error Logging?

Error logging is the process of capturing and recording runtime errors that occur in your React app — whether they’re caused by network issues, API failures, or component crashes. Without proper logging, you won’t know when or why your app failed in production.

A. Using Sentry for Error Tracking

Sentry is one of the most popular tools for real-time error monitoring in frontend and backend apps.

Features:

  • Captures runtime exceptions (JS errors, failed API calls)
  • Shows stack traces and impacted users
  • Integrates with Slack, GitHub, and CI/CD tools

Setup in React:

  1. Install Sentry SDK

    npm install @sentry/react @sentry/tracing
    
  2. Initialize in your app (e.g., index.js)

    import * as Sentry from "@sentry/react";
    import { BrowserTracing } from "@sentry/tracing";
    
    Sentry.init({
      dsn: "<https://your-dsn-link.sentry.io/>",
      integrations: [new BrowserTracing()],
      tracesSampleRate: 1.0, // capture 100% of transactions
    });
    
  3. Capture errors manually (optional)

    try {
      throw new Error("Manual error");
    } catch (error) {
      Sentry.captureException(error);
    }
    
  4. Wrap components in Sentry’s ErrorBoundary

    <Sentry.ErrorBoundary fallback={<p>Something went wrong!</p>}>
      <App />
    </Sentry.ErrorBoundary>
    

B. Using LogRocket for Session Replay

LogRocket lets you replay user sessions, so you can see exactly what led to an error.

Features:

  • Records user interactions (clicks, scrolls, navigation)
  • Logs console errors, network requests, and Redux actions
  • Integrates with Sentry or Datadog

Setup:

npm install logrocket
import LogRocket from "logrocket";

LogRocket.init("your-org/your-project");

// Optional: identify users
LogRocket.identify("USER_ID", {
  name: "John Doe",
  email: "[email protected]",
});

Use both Sentry (for error logs) and LogRocket (for user behavior) to get a complete debugging view.

2. Performance Monitoring – Track Runtime Performance

  • Performance issues can make even the best React apps feel sluggish.
  • Monitoring tools help you detect slow renders, long load times, and memory leaks.

Built-in React Tools

React Profiler (DevTools)

React DevTools has a Profiler tab to analyze:

  • Component render times
  • Re-renders and wasted renders
  • Mounting/unmounting times

You can access it in Chrome → DevTools → Profiler Tab

Example:

import { Profiler } from "react";

function onRenderCallback(
  id, // Profiler id
  phase, // "mount" or "update"
  actualDuration, // Time spent rendering
  baseDuration
) {
  console.log(`${id} took ${actualDuration}ms`);
}

<Profiler id="App" onRender={onRenderCallback}>
  <App />
</Profiler>;

Third-Party Tools for Performance Monitoring

  1. Sentry Performance Monitoring
    • Tracks slow network requests, render times, and React transactions.
  2. Google Lighthouse (via Chrome DevTools)
    • Measures performance, accessibility, and SEO.
  3. New Relic / Datadog
    • Enterprise-grade monitoring for full-stack apps (frontend + backend).
  4. Web Vitals Tracking
    • Track Core Web Vitals (LCP, FID, CLS) using Google’s web-vitals package:

      npm install web-vitals
      
      import { getCLS, getFID, getLCP } from "web-vitals";
      
      getCLS(console.log);
      getFID(console.log);
      getLCP(console.log);
      

3. Handling Runtime Errors – Graceful Fallbacks

Even with monitoring, errors will still occur in production — due to APIs, user data, or browser limitations.

That’s why React provides Error Boundaries and Fallback UI techniques.

A. React Error Boundaries

Error boundaries are React components that catch JavaScript errors in child components and display a fallback UI instead of crashing the app.

Example:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    console.error("Error caught:", error, info);
  }

  render() {
    if (this.state.hasError) {
      return <h2>Something went wrong. Please try again later.</h2>;
    }
    return this.props.children;
  }
}

Usage:

<ErrorBoundary>
  <Dashboard />
</ErrorBoundary>

B. Graceful Fallbacks with Suspense

For async or data-fetching components, you can use React.Suspense to show fallback UI while loading or retrying.

Example:

const Profile = React.lazy(() => import("./Profile"));

function App() {
  return (
    <Suspense fallback={<div>Loading profile...</div>}>
      <Profile />
    </Suspense>
  );
}

C. Retry Mechanisms

Use retry logic for transient network errors (e.g., failed API calls):

async function fetchWithRetry(url, retries = 3) {
  try {
    const res = await fetch(url);
    if (!res.ok) throw new Error("Failed request");
    return res.json();
  } catch (error) {
    if (retries > 0) return fetchWithRetry(url, retries - 1);
    throw error;
  }
}

Combine retries with Toast notifications or Fallback messages to enhance UX.

Summary Table

ConceptDescriptionTools
Error LoggingCapture runtime errors and stack tracesSentry, LogRocket
Performance MonitoringTrack render and network performanceReact Profiler, Lighthouse, Sentry Performance
Runtime Error HandlingPrevent app crashes and show fallback UIError Boundaries, Suspense, Retry Logic

Tips

  • Always monitor both frontend (React) and backend (API) for better debugging.
  • Integrate error logs with Slack or Email alerts.
  • Use source maps in production for readable error traces.
  • Track user behavior leading to errors (LogRocket).
  • Regularly test your fallback UIs — users should never see a white screen.

Article 0 of 0