Course contentsShow
← React
Lesson 1302 of 2,39633. Error BoundariesFree lesson

Logging Errors to Services

Using componentDidCatch to send error reports to Sentry, LogRocket, or other monitoring services.

Logging Errors to Services

What you'll learn: How to use componentDidCatch to automatically send error reports to monitoring services like Sentry or LogRocket.


Why Log Errors to Services?

When errors happen in production, you won't see them in your console. componentDidCatch gives you the perfect hook to capture these errors and send them to external monitoring services so you can track, debug, and fix issues your users encounter.


How componentDidCatch Enables Logging

The componentDidCatch(error, errorInfo) method receives two arguments:

  • error: The actual JavaScript error object thrown
  • errorInfo: React-specific details, including the component stack trace

This is your opportunity to send this data somewhere useful before displaying your fallback UI.


The Pattern

class ErrorBoundary extends React.Component {
  state = { hasError: false };

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

  componentDidCatch(error, errorInfo) {
    // Send to monitoring service
    logErrorToService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}

function logErrorToService(error, errorInfo) {
  // Example: Sentry.captureException(error, { extra: errorInfo });
  // Example: LogRocket.captureException(error, { tags: errorInfo });
  console.error('Logging to service:', error, errorInfo);
}

Think of It Like This

getDerivedStateFromError is the emergency responder showing users a calm "we've got this" message. componentDidCatch is the detective filing the incident report with headquarters so the team can investigate later.


Key Takeaway: Use componentDidCatch to send error details (error object + component stack) to monitoring services, enabling you to track and fix production errors you'd never see otherwise.