Search code examples
reactjsreact-router

React-Router route loader always runs twice


I am using react-router's route loader feature to fetch data before the page is loaded. My issue is that the fetch request is being made twice on initial page load.

Using the react profiler Chrome Extension I can see that the App component is loaded once on initial render and that the RouterProvider component is loaded once on render then once again when "hook 1" changes. "hook 1" includes the loader data, it appears to me that the loader function running triggers a re-render of the RouterProvider which then again runs the loader function.

Code below will reproduce my issue.

const App = () => {
  const router = createBrowserRouter([
        {
          path: "/", element: <HomePage />,
          loader:  () => {
            return fetch(`google.com/services/homepage-tags`);
          },
        },
  ]);

  return <RouterProvider router={router} />;
};

export default App;

Solution

  • The issue was with defining the router within the App function. Defining it outside of the function resolved my issue.