Skip to main content
The Sentry React SDK extends the Browser SDK with React-specific features including ErrorBoundary, Profiler components, and React Router integrations.

Installation

npm install @sentry/react

Basic Setup

Initialize Sentry before mounting your React application:
import React from 'react';
import { createRoot } from 'react-dom/client';
import * as Sentry from '@sentry/react';
import App from './App';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  
  integrations: [
    Sentry.browserTracingIntegration(),
    Sentry.replayIntegration(),
  ],
  
  // Performance Monitoring
  tracesSampleRate: 1.0,
  
  // Session Replay
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
});

const container = document.getElementById('root');
const root = createRoot(container);
root.render(<App />);

React 19 Error Handling

Starting with React 19, use the new error hooks for automatic error capture:
import { createRoot } from 'react-dom/client';
import * as Sentry from '@sentry/react';

const container = document.getElementById('root');
const root = createRoot(container, {
  // Callback called when an error is thrown and not caught by an Error Boundary
  onUncaughtError: Sentry.reactErrorHandler((error, errorInfo) => {
    console.warn('Uncaught error', error, errorInfo.componentStack);
  }),
  
  // Callback called when React catches an error in an Error Boundary
  onCaughtError: Sentry.reactErrorHandler(),
  
  // Callback called when React automatically recovers from errors
  onRecoverableError: Sentry.reactErrorHandler(),
});

root.render(<App />);

ErrorBoundary Component

Catch React component errors and display fallback UI:
import * as Sentry from '@sentry/react';

function FallbackComponent() {
  return <div>An error has occurred</div>;
}

function App() {
  return (
    <Sentry.ErrorBoundary fallback={FallbackComponent} showDialog>
      <YourComponents />
    </Sentry.ErrorBoundary>
  );
}

Profiler Component

Track React component render performance:
import * as Sentry from '@sentry/react';

function MyComponent() {
  return (
    <div>
      <ExpensiveComponent />
      <AnotherComponent />
    </div>
  );
}

// Wrap component to track render performance
export default Sentry.withProfiler(MyComponent);

React Router Integration

Sentry supports all major versions of React Router:
import * as Sentry from '@sentry/react';
import { useEffect } from 'react';
import {
  createBrowserRouter,
  RouterProvider,
} from 'react-router-dom';

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  integrations: [
    Sentry.reactRouterV6BrowserTracingIntegration({
      useEffect,
    }),
  ],
  tracesSampleRate: 1.0,
});

const sentryCreateBrowserRouter = Sentry.wrapCreateBrowserRouterV6(
  createBrowserRouter
);

const router = sentryCreateBrowserRouter([
  {
    path: '/',
    element: <Home />,
  },
  {
    path: '/about',
    element: <About />,
  },
]);

function App() {
  return <RouterProvider router={router} />;
}

TanStack Router Integration

For TanStack Router (formerly React Location):
import * as Sentry from '@sentry/react';
import { createRouter } from '@tanstack/react-router';

const router = createRouter({
  // your router config
});

Sentry.init({
  dsn: 'YOUR_DSN_HERE',
  integrations: [
    Sentry.tanstackRouterBrowserTracingIntegration(router),
  ],
  tracesSampleRate: 1.0,
});

Redux Integration

Create a Sentry Redux enhancer:
import * as Sentry from '@sentry/react';
import { createStore, compose } from 'redux';
import rootReducer from './reducers';

const sentryReduxEnhancer = Sentry.createReduxEnhancer({
  // Optionally configure
  actionTransformer: (action) => {
    // Transform or filter actions
    return action;
  },
  stateTransformer: (state) => {
    // Transform or filter state
    return state;
  },
});

const store = createStore(
  rootReducer,
  compose(sentryReduxEnhancer)
);

Performance Monitoring

Component Tracking

import * as Sentry from '@sentry/react';

function ExpensiveComponent() {
  // Track this component's render performance
  Sentry.useProfiler('ExpensiveComponent');
  
  // Component logic
  return <div>Content</div>;
}

Custom Spans

import * as Sentry from '@sentry/react';

function DataFetchingComponent() {
  const fetchData = async () => {
    await Sentry.startSpan(
      {
        name: 'fetch-user-data',
        op: 'http.client',
      },
      async () => {
        const response = await fetch('/api/user');
        return response.json();
      },
    );
  };
  
  return <div>...</div>;
}

ErrorBoundary Configuration

The ErrorBoundary component accepts these props:
  • fallback: React element or render function to display when error occurs
  • showDialog: Show Sentry user feedback dialog
  • dialogOptions: Options for the feedback dialog
  • onError: Callback when error is caught
  • onReset: Callback when error boundary is reset
  • onMount: Callback on component mount
  • onUnmount: Callback on component unmount
  • beforeCapture: Modify scope before error is sent
  • handled: Override whether error is marked as handled
<Sentry.ErrorBoundary
  fallback={({ error, componentStack, resetError }) => (
    <ErrorFallback error={error} reset={resetError} />
  )}
  showDialog
  dialogOptions={{
    title: 'Something went wrong',
    subtitle: 'Our team has been notified',
  }}
  onError={(error, componentStack, eventId) => {
    logErrorToService(error, eventId);
  }}
  beforeCapture={(scope) => {
    scope.setLevel('fatal');
  }}
>
  <App />
</Sentry.ErrorBoundary>

Best Practices

Multiple Boundaries

Use multiple ErrorBoundary components at different levels of your component tree.

Profile Wisely

Only wrap components where you need render performance data.

Router Integration

Always use router integrations for accurate transaction names.

User Feedback

Enable showDialog to collect user feedback on errors.

Next Steps

React Router

Set up router performance tracking

Redux

Integrate with state management

Error Boundaries

Advanced error boundary patterns

Profiling

Component performance profiling