Dispatch redux actions with history.listen on location change in React Router v5
history listener with useEffect hook

Let’s assume you need to call (dispatch) some redux action every time the web browser history location (pathname) is changed.
For React Router v4 I found this solution using a custom history, set the listener like this (source) and pass it to <Router />
component.
But, I’m using React Router v5.2 and looks like it prefers to use <BrowserRouter />
instead of <Router />
.
Ok, no problem, let’s make some extra component, HistoryListener.js
And now my App.js looks like:
// App.js// ... importsconst App = () => (
<Provider store={store}>
<BrowserRouter>
<HistoryListener> // <-- here we added our component
<AppRoutes />
</HistoryListener>
</BrowserRouter>
</Provider>
);
Now, when we init our web application, the loader <p>Loading...</p>
will be rendered, then someAction()
and setIsFirstRender(false)
will be called. So, we have dispatched the action we needed on the first render and now we return the children component <AppRoutes />
, but also it was created a history listener that dispatches the action on every history change.
I am pretty sure you could also use async actions with redux-thunk inside the useEffect() in HistoryListener.js.
Clap if it was useful :)