Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router v6 history.listen

In React Router v5 there was a listen mehtode on the history object. With the method I wrote a usePathname hook to rerender a component on a path change. In React Router v6, this method no longer exists. Is there an alternative for something like this? I would hate to use useLocation because it also renders if the state changes, which I don't need in this case.

The hook is used with v5.

import React from "react";
import { useHistory } from "react-router";

export function usePathname(): string {
  let [state, setState] = React.useState<string>(window.location.pathname);

  const history = useHistory();
  React.useLayoutEffect(
    () =>
      history.listen((locationListener) => setState(locationListener.pathname)),
    [history]
  );
  return state;
}
like image 339
Hummel37 Avatar asked Sep 09 '25 21:09

Hummel37


1 Answers

As mentioned above, useLocation can be used to perform side effects whenever the current location changes.

Here's a simple typescript implementation of my location change "listener" hook. Should help you get the result you're looking for

function useLocationEffect(callback: (location?: Location) => any) {
  const location = useLocation();

  useEffect(() => {
    callback(location);
  }, [location, callback]);
}

// usage:
useLocationEffect((location: Location) => 
  console.log('changed to ' + location.pathname));
like image 188
yuval.bl Avatar answered Sep 12 '25 13:09

yuval.bl