Search code examples
reactjsreact-routerhookrouter

How to listen to route change in hookrouter - React


I know that react-router provides onChange attribute to listen to route change, but I'm using hookrouter package (doc).

I'm trying to get a log of users when they visit a specific route. For e.g. when they visit /aboutus route. The user could visit through button click, entering URL manually or opening a bookmarked page.

There are tracking apps available which tracks counter on button click but I haven't find any app that keeps track of how many times a specific route was visited by the user.

In short, is there a way I know how many times the user visited a specific route?


Solution

  • This library is quite limited compared to react-router but you can detect when a path changes by using the following hook:

    const currentPath = usePath();
    
    useEffect(() => {
      // Do something with currentPath
    }, [currentPath]);
    

    In this effect, you can do a page track or log an event.

    Provided that this code is at the root of your app (or somewhere it can run globally) and that the path is passed to the list of dependencies, it will fire whenever the path changes.

    Docs for usePath