Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

298
Vistas
How to avoid re-initializing component when multiple linked routes use same component

I have a react-router-dom component that was all working fine in v5, and I have since upgraded to v6. In the below router structure, I have a single component that is accessed via different routes. This view has a playback feature that updates the URL when playback is stopped resulting in a foo/<fooId>/<time> url structure, and a means to link to something in the list with bar/<barId>. Both of these render the same component, that uses the params as need be and can handle both entry points.

The issue I'm seeing since moving to v6 is it will refresh if switching from foo/<fooId>/<time> to bar/<barId> or viceversa. Same happens if I click a link to bar/<barId> while on foo/<foodId>/time. It's the same component, and simply updated the browser URL in the past (used to use history.pushState and now use navigate (from useNavigate), I tried adding a replace param, etc., but it still re-mounts the entire component.

How can I avoid this? I can only think to re-structure the pages, but there's a bunch of bookmarks out there that will be very unhappy, haha.

      <Route
        path="/foo"
        element={<AuthedRoute authState={authState} element={<Bar />} />}
      >
        <Route
          path=":fooId"
          element={<AuthedRoute authState={authState} element={<Bar />} />}
        />
        <Route
          path=":fooId/:timestamp"
          element={<AuthedRoute authState={authState} element={<Bar />} />}
        />
      </Route>
      <Route path="/bar">
        <Route
          path=":barId"
          element={<AuthedRoute authState={authState} element={<Bar />} />}
        />
      </Route>

AuthRoute:

function AuthedRoute({ authState, element }) {
  const location = useLocation()
  const { isLoggedIn } = authState
  return isLoggedIn ? (
    element
  ) : (
    <Navigate
      to="/login"
      state={{
        from: location,
      }}
    />
  )
}

Similar structure to the example here

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Shoot, ok, I hadn't noticed that you had nested "/foo" and "/bar" routes. That changes things a bit. I was able to reproduce the issue of switching between "/foo" and "/bar" routes. I still suggest converting the AuthedRoute into a layout component and rendering an Outlet for nested routes you want to protect.

function AuthedRoute({ authState }) {
  const location = useLocation();
  const { isLoggedIn } = authState;
  return isLoggedIn ? (
    <Outlet />
  ) : (
    <Navigate
      to="/login"
      state={{
        from: location
      }}
    />
  );
}

Next is to configure/structure your routes so the are correctly nested. The following structure seems to work as you are expecting.

<Routes>
  <Route element={<AuthedRoute authState={authState} />}>
    <Route path="/foo/*">
      <Route index element={<Bar />} />
      <Route path=":fooId" element={<Bar />} />
      <Route path=":fooId/:timestamp" element={<Bar />} />
    </Route>
    <Route path="/bar/*">
      <Route path=":barId" element={<Bar />} />
    </Route>
  </Route>
  <Route path="/login" element={<Login /* auth props? */ />} />
</Routes>

For testing when Bar component was mounted vs rendered (an id prop was passed to each to identify them):

const Bar = ({ id }) => {
  useEffect(() => {
    console.log("Bar MOUNTED!!", { id });
  }, []);

  useEffect(() => {
    console.log("Bar Rendered!!", { id });
  }, [id]);

  return <h1>Bar</h1>;
};

After authenticating, use the links to navigate between all the different routes and note when "Mounted" vs "Rendered" logs.

Here's my running codesandbox:

Edit how-to-avoid-re-initializing-component-when-multiple-linked-routes-use-same-comp

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda