-1

There is a main component that handles everything, and I want to show the same main component whenever the URL parameter changes.

So I made this Browser Router structure.


function Router() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="main" element={<Main />}>
          <Route path=":id" element={<Main />} />
          <Route path="lists/:listId/tasks" element={<Main />} />
          <Route path="lists/:listId/tasks/:id" element={<Main />} />
          <Route path="all/tasks" element={<Main />} />
          <Route path="all/tasks/:id" element={<Main />} />
        </Route>
        <Route path="signup" element={<SignUp />} />
        <Route path="signin" element={<SignIn />} />
        <Route
          path="requestUpdatePassword"
          element={<RequestUpdatePassword />}
        />
        <Route path="*" element={<NotFound />} />
      </Routes>
    </BrowserRouter>
  );
}

This causes the main component to be re-rendered every time the URL changes, resulting in poor performance. In v5, I could assign string[] to path of Route, but in v6, I couldn't assign an array.

How can I display multiple URLs in the same component without re-rendering?

ni-so
  • 1
  • See this answer - https://stackoverflow.com/questions/40541994/multiple-path-names-for-a-same-component-in-react-router – Mile Mijatović Jun 19 '22 at 15:39
  • Wouldn't you ***want*** the `Main` component to rerender when the path, and path params, its rendered on changes? Based on your question this is indicative of a code smell and you are likely asking a XY question. What is `Main` doing that simply rerendering it is a problem? Can you update the post to include a [minimal, complete, and reproducible code example](https://stackoverflow.com/help/minimal-reproducible-example) that includes all relevant code you have an issue working with? – Drew Reese Jun 20 '22 at 18:35

1 Answers1

0

I'd use a simple Layout to handle your components

In your case, I assume you're worried about your component being re-rendered every time you reload your route.

Instead, you can do the following:

<BrowserRouter>
  <MyHeader>
    <Routes>
      [...] // whichever components you want to render in your header
    </Routes>
  </MyHeader>
  <MyContent>
    <Routes>
      [...] // whichever components you want to render in your content
    </Routes>
  </MyContent>
  <MyFooter>
    <Routes>
      [...] // whichever components you want to render in your footer
    </Routes>
  </MyFooter>
</BrowserRouter>

This way, you make sure that only the content of your layout gets re-rendered.

I'd strongly suggest you take a look at the documentation for V6, for they added a lot of features that would heavily ease up your development process.

Pierre Olivier Tran
  • 1,669
  • 4
  • 24
  • 40