React router doesn't refresh page

Viewed 2337

I have two different routes that are using the same component.


    <BrowserRouter>
      <Routes>  
        <Route path="/produktai" element={<Products />}/>
        <Route path="/produktai/:productId" element={<Products />} />
      </Routes>
    </BrowserRouter>

I'm using Link from react to switch between pages and get id's from


    const pathname = useLocation().pathname;

to perform rest api's.

For example, when i change pages using Link from /products to /products/2, url changes but the problem is that page doesn't refresh as it should. Problem solves if i'm using a tag with href as it always reloads page unlike smooth react Link functionality but i don't think that's a good solution.

2 Answers

Even though the route path changes you are still rendering the same Products component. If you need to run some logic when the path changes, or more likely, when the productId route param updates, then you should use an useEffect hook with the productId route param as a dependency.

Example:

const { productId } = useParams();

useEffect(() => {
  if (productId) {
    // Perform rest api call and response handling
  }
}, [productId]);

There is a better approach for this issue. Give unique keys like below.

    <Route path="/all-reports">
        <ReportsPage key="1" />
    </Route>
    <Route path="/shared-reports">
        <ReportsPage key="2" mode="shared" />
    </Route>
    <Route path="/owned-reports">
        <ReportsPage key="3" mode="owned" />
    </Route>
Related