0

I have 2 routes which render the same component.

Once I am on route path "/route1", I click on a link which routes me to /route2. I expect componentWillUnmount() to be called but instead the render method is called again with prop type "type2". Why is this happening?

I have already tried adding a key to each Route but it does not work.

`<Switch>
         <Route
          path={'/route1'}
          render={props => (
            <Component1
              type={type1}
              {...props}
            />
        )}
      />
      <Route
        path={'/route2'}
        render={props => (
          <Component1
            type={type2}
           {...props}
          />
        )}
      />
    </Switch>`
  • 1
    Why are both routes pointing to the same thing? React's virtual dom diffing is _smart_ so it has no reason to waste time on unmounting a component and then mounting _exactly the same component_, it's just going to update the one that's already there. – Mike 'Pomax' Kamermans Aug 29 '19 at 21:52
  • 1
    you actually may force re-creating component by providing different `key` prop. but refactoring component so it would respect `componentDidUpdate` looks more promising in long term. – skyboyer Aug 29 '19 at 21:54
  • Possible duplicate of [Component does not remount when route parameters change](https://stackoverflow.com/questions/32261441/component-does-not-remount-when-route-parameters-change) – skyboyer Aug 29 '19 at 21:57
  • @skyboyer Where do I add key? The reason I am using the same component for different routes it that I have a navigation menu with different categories. So, if use clicks on category1, I change the route to /category1, make an API call in componentdidmount() and store it in redux store. Now if user clicks on category2, I want to make an API call to fetch category2 data and store it in the redux store. However, here the render method is called with the data of category1 api call before componentWillUnmount() is called. – Abhishek Oza Aug 29 '19 at 22:00
  • Not even componentDidUpdate() is called when the route changes. It always goes to render() method first – Abhishek Oza Aug 29 '19 at 22:02
  • `render={props => ( – skyboyer Aug 29 '19 at 22:20

0 Answers0