Home > Software engineering >  How to prevent layout loader in React Router 6 from being called multiple times when children redire
How to prevent layout loader in React Router 6 from being called multiple times when children redire

Time:12-16

I have the following router config:

const router = createBrowserRouter([
  {
    element: <Layout />,
    loader: loaderFunction,
    children: [
      {
        path: '/home',
        element: <HomePage />
      },
      {
        path: '/about',
        element: <AboutPage />
      },
      {
        path: '/contact',
        element: <ContactPage />
      },
    ],
    errorElement: <ErrorPage />
  },
  {
    path: '*',
    element: <NotFoundPage />
  }
]);

This config has a <Layout /> parent, with several child routes (and their respective components).

The reasoning for this is that if a user enters any of those paths directly, the same behavior should occur.

Namely, the loaderFunction should fetch data. Then within the <Layout /> the data is parsed and analyzed... and then using the information the user is redirected using conditions like so:

if (conditionA && pathname !== '/about') {
  return <Navigate to="/about" replace />
}

if (conditionB && && pathname !== '/contact') {
  return <Navigate to="/contact" replace />
}

return <Outlet />;

The problem is that when a redirect points to one of those child components, the loaderFunction is re-triggered resulting in multiple server calls.

Is there a built-in way to manage this to avoid this problem? Or perhaps there is a better pattern for how to program this?

CodePudding user response:

shouldRevalidate flag setting to false solves your problem;

It gives you control on preventing loader calls.

const router = createBrowserRouter([
  {
    element: <Layout />,
    loader: loaderFunction,
    shouldRevalidate: () => false,
  }
])  

documentation

  • Related