Skip to content

bug: Ionic React useIonRouter returns unstable reference causing maximum update depth error in useEffect #24987

@babycourageous

Description

@babycourageous

Prerequisites

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions