Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent re-render of parent route using React-Router and Framer Motion?

I'm using Framer Motion with React Router to create animations between different routes.

I followed this tutorial: https://www.youtube.com/watch?v=qJt-FtzJ5fo

I'll try to summarize the problem in the following points:

I'm using React Router v6 for routing, I have multiple nested routes and parallel switches for different components on my app, which is a simple catalog.

I've added transitions to each page's {content} component and leaving the {footer} and {header} components on different switches to prevent them from animating.

I've also added location={location} key={location.pathname} to the switch component and exitBeforeEnter to the AnimatePresence wrapper.

The issue becomes apparent when accesing one of the catalog's items, whose route is "es/:catalogid/:id", which is dynamic and shown as an overlay over the previous page. Accesing these routes affects the previous route, located at "/es/", and triggering the animation.

How would one go about preventing this issue?

Framer Motion and React router 5: How do I prevent re-render of parent components with nested routes? this is almost exactly the same issue, but the codesandboxes are not working and the solution isn't either.

Thanks for reading.

like image 716
Alonso Tijero Larrabure Avatar asked Dec 19 '25 10:12

Alonso Tijero Larrabure


1 Answers

Sharing your code might help to add some clarity on implementation.

My guess is that setting key={location.pathname} on your Switch component is causing a re-render of the whole page, which is then triggering the animation.

React Router's location.pathname is tied to the current url. As an example if you go from the route es/myItems to es/myItems/myFirstItemDetail, that will be reflected in location.pathname

It doesn't matter if the catalog's route is nested, when a parent component's key changes, React will re-render that parent and all child elements.

From "4 methods to force a re-render in React":

By changing the value of the key prop, it will make React unmount the component and re-mount it again, and go through the render() lifecycle.

I also found this explainer helpful: Understanding React's Key Prop

Try using a different value for that Switch's key that's not dependent on stuff happening with its children.

like image 134
goodmorningasif Avatar answered Dec 21 '25 00:12

goodmorningasif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!