Created
November 27, 2023 21:56
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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