Search code examples
reactjsreact-routerreact-router-dom

React router does not reload component if same element is used for two paths


I have the following two paths set up

<Route path="bookings/:bookingnumber" element={<Bookings />} />
<Route path="bookings" element={<Bookings />} />

In Bookings component I have conditional code written to check if a parameter :bookingnumber is passed, and then it only shows results relevant to that booking number. Otherwise, if no parameter is passed, it shows all the results for all the bookings.

I am using Outlet to display these components in the main area, and the two paths can be chosen from a sidebar.

Let's say I have 10 results if I go to /bookings, and 2 results if I go to /bookings/123.

However, if I go to /bookings/123 first and then to /bookings it keeps on showing only 2 results (the component does not reload, however I can see the URL changing in the browser)


Solution

  • Issue

    <Route path="bookings" element={<Bookings />} />
    <Route path="bookings/:bookingnumber" element={<Bookings />} />
    

    With the same component rendered on more than 1 route, if you navigate from one route to another for the same routes component, the routed component remains mounted.

    Example: If navigating from "/bookings" to "/bookings/123", or "/bookings/123" to "/bookings", or "/bookings/123" to "/bookings/456" the Bookings component remains mounted. If you've any logic that depends on the bookingnumber route path parameter then the Bookings component needs to handle this in a useEffect hook with a proper dependency on the bookingnumber param.

    Solution

    Use a useEffect hook to "listen" for changes to the bookingnumber param value.

    Example:

    const Bookings = () => {
      const { bookingnumber } = useParams();
    
      useEffect(() => {
        // initial render or booking number value updated
        // run logic depending on bookingnumber value to update "results"
        ... 
      }, [bookingnumber]);
    
      ...
    };