question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

React Hooks issue with react-router-v6 integration

See original GitHub issue

Is there an existing issue for this?

How do you use Sentry?

Sentry Saas (sentry.io)

Which package are you using?

@sentry/react

SDK Version

7.2.0

Framework Version

7.2.0

Steps to Reproduce

1. Starting a react application with Vite.js in dev mode with react-refresh 2. Adding a simple Application like this one

import React from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter, useLocation, useNavigationType, createRoutesFromChildren, matchRoutes, Routes, Route } from 'react-router-dom';
import * as Sentry from '@sentry/react';
import { BrowserTracing } from '@sentry/tracing';
import { APP_ENVIRONMENT, SENTRY_DSN } from './config';

Sentry.init({
    dsn: SENTRY_DSN,
    integrations: [
        new BrowserTracing({
            routingInstrumentation: Sentry.reactRouterV6Instrumentation(React.useEffect, useLocation, useNavigationType, createRoutesFromChildren, matchRoutes),
        }),
    ],
    environment: APP_ENVIRONMENT,
    tracesSampleRate: 1.0,
});

const SentryRoutes = Sentry.withSentryReactRouterV6Routing(Routes);


function render() {
    const container = document.getElementById('root');
    if (!container) {
        return null;
    }
    const root = createRoot(container);
    root.render(
        <React.StrictMode>
            <BrowserRouter>
                <SentryRoutes>
                    <Route path="/" element={<React.Fragment />} />
                </SentryRoutes>
            </BrowserRouter>
        </React.StrictMode>,
    );
}

(() => {
    render();
})();

Same code is in the official doc of Sentry https://docs.sentry.io/platforms/javascript/guides/react/configuration/integrations/react-router/ 3. The app starts normally in dev mode. 4. As soon as I perform one modification, the front-end application crash completely. I need to close the tab and stop the application.

When I remove

new BrowserTracing({
            routingInstrumentation: Sentry.reactRouterV6Instrumentation(React.useEffect, useLocation, useNavigationType, createRoutesFromChildren, matchRoutes)
})

from the sentry integrations, everything goes back to normal

Expected Result

When I do a change in local while I am developing, I should see my changes in live without my app crashing. I should be able to use BrowserTracing with Sentry without my app having issues

Actual Result

Warning: React has detected a change in the order of Hooks called by SentryRoutes. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks

There is issue in the order of hooks execution while adding the BrowserTracing from Sentry. Screenshot 2022-06-24 at 18 19 44

Vite.js config to start the app.

import { defineConfig, loadEnv } from 'vite';
import { visualizer } from 'rollup-plugin-visualizer';
import react from '@vitejs/plugin-react';
import svgrPlugin from 'vite-plugin-svgr';

export default defineConfig(({ mode }) => {
    const env = loadEnv(mode, process.cwd());

    // expose .env as process.env instead of import.meta since jest does not import meta yet
    const envWithProcessPrefix = Object.entries(env).reduce((prev, [key, val]) => {
        return {
            ...prev,
            ['process.env.' + key]: `"${val}"`,
        };
    }, {});

    return {
        server: {
            port: 3000,
        },
        preview: {
            port: 8080,
        },
        define: envWithProcessPrefix,
        build: {
            sourcemap: true,
            outDir: 'build',
            minify: 'esbuild',
        },
        plugins: [
            react(),
            svgrPlugin({
                svgrOptions: {
                    // ...svgr options (https://react-svgr.com/docs/options/)
                },
            }),
            visualizer(),
        ],
    };
});

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
onurtemizkancommented, Sep 1, 2022

Hey @alexabidri,

After debugging the reproduction, I was able to fix the issue by initializing Sentry at App.tsx instead of main.tsx.

The problem is, the routes were never actually wrapped, because Sentry.withSentryReactRouterV6Routing was called before the initialization (App.tsx runs before main.tsx).

If HMR refreshes App.tsx, it tries to wrap Routes again, and succeeds this time, because the initialization is already happened. But it conflicts, as the hook order of the wrapped Routes is not matching the non-wrapped one, which is already rendered.

Not sure if we can do anything on the SDK side. But I’ll add a note to the docs, reminding users to make sure init runs before the wrapper.

1reaction
alexabidricommented, Jun 30, 2022

@onurtemizkan No problem, here it is https://github.com/alexabidri/vite-sentry 🙏

1 - Start the app with npm run dev 2 - Modify the wording TEST into something else here https://github.com/alexabidri/vite-sentry/blob/main/src/App.tsx#L11, it will trigger react hot reloading 3 - Your app will crash and the browser also with, with a issue related to Sentry React Router v6 integration (hooks issue)

Read more comments on GitHub >

github_iconTop Results From Across the Web

Migrating to React Router v6: A complete guide
Migrate your React Router applications from v5 to v6 with this in-depth guide, including a review of additions and improvements from v5.
Read more >
Redirect in React Router V6 with useNavigate hook - Refine Dev
Configure your app to start using React Router by importing the router and wrapping your root component in it. Since our goal is...
Read more >
ReactJS error on using hooks with react router dom v6
ReactJS error on using hooks with react router dom v6 · 1. You might have mismatching versions of React and the renderer (such...
Read more >
useLocation v6.6.1 - React Router
This hook returns the current location object. This can be useful if you'd like to perform some side effect whenever the current location...
Read more >
useLoaderData v6.6.1 - React Router
This also means data returned is stable between renders, so you can safely pass it to dependency arrays in React hooks like useEffect...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found