IonPage: useEffect with history.listen

I am wondering if it’s safe to use history.listen inside a useEffect on an IonPage.


    useEffect(() => {
        return history.listen((location): void => {
            if (location.pathname === '/hello') {
                // do stuff 
    }, []);

My concern is that the returned function from listen() not being called and unregistering the listener. IonPage's (from my experience) don’t always unmount as expected and the above create multiple listeners every time this page was loaded/rendered.

1 Like

I’m not sure what you’re trying to do, but one way I got around the multiple listeners problem is to put a single listener directly in the router like this:

    <ListenerAppRouterAnalytics />
      <Route exact path="/">
        <Redirect to={routeTabWelcome} />

And then my component:

const ListenerAppRouterAnalytics: React.VFC = () => {
  const location = useLocation();

  // Set the screen name for each router path.
  useEffect(() => {
    const path = location.pathname +;
    // console.log('setting screenName for path', path);
  }, [location]);

  return null;

I’m not sure if this is the best approach but I haven’t noticed any problems so far.

I’m was trying to determine the best to listen for route changes to do certain actions based on the route. I actually ended for using hook useLocation in my use case.