Reactjs Render on Router (url) change

I would like to use a function on every url change while using

I know UseEffect will load on every page reload or startup but i want it to load on every < Link > change.

i have tried a couple of things that i saw on old websites and posts but it seems to be out-dated:

what i have tried:

import { useHistory } from 'react-router';

function app(){
  const history = useHistory() 

 useEffect(() =>{
    return history.listen((location) => {
      console.log("new page:", location.pathname)

import { useHistory } from 'react-router-dom';

Did not work either

TypeError: Cannot read property ‘listen’ of undefined

  40 | const history = useHistory() 
  41 | 
  42 | useEffect(() =>{
> 43 |   return history.listen((location) => {
     | ^  44 |     console.log("new page:", location.pathname)
  45 |   })
  46 | },[history])
1 Like
 const history = useHistory()

    useEffect(() => {
        return history.listen((location) => {
            console.log(`You changed the page to: ${location.pathname}`)

Changing the console log message had no effect, the problem is the “return” part

That’s quite correct, the return part is the problem, because returning from useEffect means that whatever code you return runs only when the component unmounts. So, removing the return keyword should fix it.

Thank you for the reply,
unfortnualy it still gives the same error

TypeError: Cannot read property ‘listen’ of undefined

  43 | useEffect(() => {
> 44 |     history.listen((location) => {
     | ^  45 |         console.log(`You changed the page to: ${location.pathname}`)
  46 |     })
  47 | },[history])

I don’t think you can use it in a component like that, history will be undefined.

Create the Router/Switch/Route in App and then use the hook in one of the route components. Also, just to be clear, history.listen returns an cleanup function you can use inside useEffect for the cleanup (to unlisten).

What exactly are you trying to do inside the history listener? You might also look at the useLocation hook.

Not sure this example is of much use but anyway.

I basicly want to create a Analytics function so everytime it goes to a new url (using Link) i want a function to run so i can use fetch and send that data to the back-end so it can put it in the database.

But If anyone has a better idea please let me know

The docs have an example of the useLocation hook with google analytics.

You can create a custom hook as shown and use that in the App component. Although, I do find the docs on both hooks fairly lacking. Not really sure what the rules are for using them but with this hook it seems the App component has to be inside the Router.


This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.