T
TanStack•7mo ago
like-gold

useNavigate to change search params without remounting the route componen

I'm trying to use useNavigate() to change just the search params, but it unnecessarily flashes due to unmounting and mounting the route component again. Is there a mode of operation where it "just" updates the URl with history push but doesn't re-mount the Route component? My code:
export const Route = createFileRoute("/route/")({
validateSearch: (search) => {
return searchSchema.parse(search);
},
beforeLoad: ({ search }) => {
return {
// ...
};
},
component: RouteComponent,
});

function RouteComponent() {
const search = useRouteContext({from: "/route/", select: ({search}) => search});
const navigate = useNavigate({from: "/route"});
const id = search.id;
const setId = (name: string) => {
navigate({search: {id: name}})
};
useEffect(() => {
console.warn("mounted");
return () => console.warn("unmounted");
});
export const Route = createFileRoute("/route/")({
validateSearch: (search) => {
return searchSchema.parse(search);
},
beforeLoad: ({ search }) => {
return {
// ...
};
},
component: RouteComponent,
});

function RouteComponent() {
const search = useRouteContext({from: "/route/", select: ({search}) => search});
const navigate = useNavigate({from: "/route"});
const id = search.id;
const setId = (name: string) => {
navigate({search: {id: name}})
};
useEffect(() => {
console.warn("mounted");
return () => console.warn("unmounted");
});
and when I call setId, it remounts. Due to the vdom, if this remount does not hit any loading state, the navigation is pretty seamless, but if there's anything in loader or just useQuery within the component, it will flash. As a workaround, I've added navigate({..., viewTransition: true}) but I'd really just like to tackle the root cause if possible.
3 Replies
flat-fuchsia
flat-fuchsia•7mo ago
the shown useEffectdoesn't do any mounting - it runs on every render because there is no dependency array since your component is subscribed to search, and you change search, a re-render is expected
like-gold
like-goldOP•7mo ago
oh that's embarassing. I've been using React Compiler too much. Yeah there's no actual re-mounting and the paint flashes must be the fault of my own component
flat-fuchsia
flat-fuchsia•7mo ago
the compiler doesn't fill in effect dependencies 😅 but I get where you're coming from

Did you find this page helpful?