T
TanStack2y ago
xenial-black

Subscribe to Route Changes

Is router.subscribe the best way to re-render a component when a route changes? I feel like I'm missing something, is there a simpler approach?
const router = useRouter();
const [matchedRouteIds, setMatchedRouteIds] = useState(
router.state.matches.map((m) => m.id)
);
useEffect(() => {
return router.subscribe("onResolved", () => {
const newMatchedRouteIds = router.state.matches.map((m) => m.id);
setMatchedRouteIds(newMatchedRouteIds);
});
}, [router]);
const isUsersRouteActive = matchedRouteIds.includes(usersRoute.id);
const router = useRouter();
const [matchedRouteIds, setMatchedRouteIds] = useState(
router.state.matches.map((m) => m.id)
);
useEffect(() => {
return router.subscribe("onResolved", () => {
const newMatchedRouteIds = router.state.matches.map((m) => m.id);
setMatchedRouteIds(newMatchedRouteIds);
});
}, [router]);
const isUsersRouteActive = matchedRouteIds.includes(usersRoute.id);
1 Reply
xenial-black
xenial-blackOP2y ago
Ok looks like there's a new useMatches() hook - and I had a buggy version of the beta

Did you find this page helpful?