Use router.subscribe to detect nav direction between parent and child
I need the navigation direction for a page transition animation.
1. Is
router.subscribe stable-ish API? It's not mentioned in any documentation.
2. Is it the best way to detect whether or not navigation is about to happen and the direction between parent and child routes?
3. Can I call router.subscribe inside a functional component? Will it remove and re-add the event listener during re-renders? Or is this a memory leak? I need to call the dispatch function provided by the useState hook inside the event listener.
I will be performing the detection like so:
6 Replies
xenial-black•2y ago
If you are calling
router.subscribe inside a React component, you'd have to do the usual useEffect stuff. Same any other event listeners.
That's the React way of solving the memory leak problem.eastern-cyanOP•2y ago
Wait, there's no
router.unsubscribe. If I understand correctly, the snippet you've provided would only subscribe to the router event after a re-renderxenial-black•2y ago
There is no
router.unsubscribe method.
When you call router.subscribe it returns a function that handles the unsubscribe functionality. This is a standard convention in the publish-subscribe model.
See Router docs here: https://tanstack.com/router/latest/docs/framework/react/api/router/createRouterFunction#subscribecreateRouter function | TanStack Router Docs
The createRouter function creates a new Router instance.
options
xenial-black•2y ago
The snippet above does not only subscribe to an event after re-render.
Instead, upon each render of the component, it calls the subscribe method. When the component is re-rendered OR removed from view, the returned unsubscribe function will be invoked in the cleanup callback of the useEffect.
This method of unsubscription is how this lifecycle is handled in React to avoid memory leaks. See React docs here: https://react.dev/reference/react/useEffect#connecting-to-an-external-system
useEffect – React
The library for web and native user interfaces
eastern-cyanOP•2y ago
Thanks! Sorry for asking something that is in the docs. I imagine the broken search doesn't help either 😅
xenial-black•2y ago
No sweat!
Unfortunately the search being broken is taking a bit longer than we'd like to get fixed.