Skip to content

Instantly share code, notes, and snippets.

@aeharding
Created November 27, 2023 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aeharding/75c0741ddb18609091c4e69289f857e1 to your computer and use it in GitHub Desktop.
Save aeharding/75c0741ddb18609091c4e69289f857e1 to your computer and use it in GitHub Desktop.
useIonRouter() has routeInfo attached. This causes a rerender of all components that contain useIonRouter, slowing down swipes. Since 99% of components don't use routeInfo and just need to push, we can optimize by using refs so rerender isn't triggered.
import { UseIonRouterResult, useIonRouter } from "@ionic/react";
import {
MutableRefObject,
ReactNode,
createContext,
useContext,
useEffect,
useMemo,
useRef,
} from "react";
type OptimizedRouterRef =
| MutableRefObject<UseIonRouterResult | undefined>
| undefined;
interface IOptimizedRouterContext {
// used for determining whether page needs to be scrolled up first
routerRef: OptimizedRouterRef;
}
const OptimizedRouterContext = createContext<IOptimizedRouterContext>({
routerRef: undefined,
});
export function useOptimizedIonRouter() {
const context = useContext(OptimizedRouterContext);
return useMemo(
() => ({
push: (...args: Parameters<UseIonRouterResult["push"]>) =>
context.routerRef?.current?.push(...args),
goBack: (...args: Parameters<UseIonRouterResult["goBack"]>) =>
context.routerRef?.current?.goBack(...args),
canGoBack: (...args: Parameters<UseIonRouterResult["canGoBack"]>) =>
context.routerRef?.current?.canGoBack(...args),
}),
[context.routerRef],
);
}
export function OptimizedRouterProvider({ children }: { children: ReactNode }) {
const router = useIonRouter();
const routerRef = useRef<UseIonRouterResult>();
useEffect(() => {
routerRef.current = router;
}, [router]);
const value = useMemo(() => ({ routerRef }), []);
return (
<OptimizedRouterContext.Provider value={value}>
{children}
</OptimizedRouterContext.Provider>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment