Handle component's mount and unmount order caused by react-router animations

593 Views Asked by At

I used CSS transitions from react-transition-group in order to make transitions between different routes animated. Below is how the code roughly looks like:

<BrowserRouter>
  <TransitionGroup>
    <CSSTransition
      timeout={350}
      classNames="page"
      key={location.key} //location is object returned by useLocation() hook
      unmountOnExit
    >
      <Switch location={location}>
        <Route path="/" component={HomeComponent} />
        <Route path="/login" component={LoginComponent} />
      </Switch>
    </CSSTransition>
  </TransitionGroup>
</BrowserRouter>

Animations work fine, but what I found is that the order in which components are being mounted and unmounted is not the way I want it to be. The thing is that If I use the same code without animations, when I go from route "/" to route "/login", firstly HomeComponent gets unmounted and only then react mounts LoginComponent. However, using animations, when the same change of route happens, firstly LoginComponent is being mounted and afterward HomeComponent is being unmounted. In my opinion, this behaviour is not obviously expected.

So the question is: is it possible to remain animated routes in my app and change this odd order in which components are being mounted and unmounted? If no, how can I know, being inside my LoginComponent, that HomeComponent is now unmounted without manipulating any global state?

0

There are 0 best solutions below