bug: Ionic React useIonRouter returns unstable reference causing maximum update depth error in useEffect
See original GitHub issuePrerequisites
- I have read the Contributing Guidelines.
- I agree to follow the Code of Conduct.
- I have searched for existing issues that already report this problem, without success.
Ionic Framework Version
- v4.x
- v5.x
- v6.x
Current Behavior
When using the router
object returned from useIonRouter
inside a useEffect
, the router must be placed in the dependency array. The useIonRouter
hook returns the object un-memoized so the dependency in useEffect
causes an infinite loop.
Expected Behavior
The object returned by useIonRouter
should be stable to be able to use in dependency arrays.
Steps to Reproduce
Run the repro - on the home page click the redirect button. It uses an effect to push to a new route. The router object is required in the dependency array and it causes the maximum update exceeded loop.
Code Reproduction URL
https://github.com/babycourageous/ionic-stable-useIonRouter
Ionic Info
Ionic:
Ionic CLI : 6.18.1 (/Users/renedellefont/.fnm/node-versions/v16.13.1/installation/lib/node_modules/@ionic/cli) Ionic Framework : @ionic/react 6.0.13
Capacitor:
Capacitor CLI : 3.4.3 @capacitor/android : not installed @capacitor/core : 3.4.3 @capacitor/ios : not installed
Utility:
cordova-res : not installed globally native-run : 1.5.0
System:
NodeJS : v16.13.1 (/Users/renedellefont/.fnm/node-versions/v16.13.1/installation/bin/node) npm : 8.1.2 OS : macOS Big Sur
Additional Information
I locally replaced the useIonRouter
supplied by Ionic with the following and it fixed the issue. The object returned is wrapped by useMemo
so that it’s a stable reference for any dependency arrays it is included in.
export function useIonRouter(): UseIonRouterResult {
const context = useContext(IonRouterContext)
return React.useMemo(
() => ({
back: context.back,
push: context.push,
goBack: context.back,
canGoBack: context.canGoBack,
routeInfo: context.routeInfo,
}),
[context.back, context.canGoBack, context.push, context.routeInfo]
)
}
The github repro is Ionic 6 but I can confirm the same issue exists in Ionic 5.
Thanks!
Issue Analytics
- State:
- Created a year ago
- Comments:7 (6 by maintainers)
@ionic/react
depends on@ionic/core
, so you need to buildcore
before you can buildreact
. You can runnpm run sync
in thereact
directory prior to buildingreact
to copy over the builtcore
changes.Thanks for confirming @liamdebeasi. I’ll look over your CONTRIB docs and get something in the queue for ya!